utils.rs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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(if matches.free.len() != free.len() {
  82. 1
  83. } else {
  84. 0
  85. })
  86. }
  87. matches
  88. }
  89. }
  90. }
  91. pub fn add_tuntap_options(opts: &mut Options, _free: &mut Vec<&str>) {
  92. opts.optopt("", "tun", "TUN interface to use", "tun0");
  93. opts.optopt("", "tap", "TAP interface to use", "tap0");
  94. }
  95. #[cfg(feature = "phy-tuntap_interface")]
  96. pub fn parse_tuntap_options(matches: &mut Matches) -> TunTapInterface {
  97. let tun = matches.opt_str("tun");
  98. let tap = matches.opt_str("tap");
  99. match (tun, tap) {
  100. (Some(tun), None) => TunTapInterface::new(&tun, Medium::Ip).unwrap(),
  101. (None, Some(tap)) => TunTapInterface::new(&tap, Medium::Ethernet).unwrap(),
  102. _ => panic!("You must specify exactly one of --tun or --tap"),
  103. }
  104. }
  105. pub fn add_middleware_options(opts: &mut Options, _free: &mut Vec<&str>) {
  106. opts.optopt("", "pcap", "Write a packet capture file", "FILE");
  107. opts.optopt(
  108. "",
  109. "drop-chance",
  110. "Chance of dropping a packet (%)",
  111. "CHANCE",
  112. );
  113. opts.optopt(
  114. "",
  115. "corrupt-chance",
  116. "Chance of corrupting a packet (%)",
  117. "CHANCE",
  118. );
  119. opts.optopt(
  120. "",
  121. "size-limit",
  122. "Drop packets larger than given size (octets)",
  123. "SIZE",
  124. );
  125. opts.optopt(
  126. "",
  127. "tx-rate-limit",
  128. "Drop packets after transmit rate exceeds given limit \
  129. (packets per interval)",
  130. "RATE",
  131. );
  132. opts.optopt(
  133. "",
  134. "rx-rate-limit",
  135. "Drop packets after transmit rate exceeds given limit \
  136. (packets per interval)",
  137. "RATE",
  138. );
  139. opts.optopt(
  140. "",
  141. "shaping-interval",
  142. "Sets the interval for rate limiting (ms)",
  143. "RATE",
  144. );
  145. }
  146. pub fn parse_middleware_options<D>(
  147. matches: &mut Matches,
  148. device: D,
  149. loopback: bool,
  150. ) -> FaultInjector<Tracer<PcapWriter<D, Box<dyn io::Write>>>>
  151. where
  152. D: for<'a> Device<'a>,
  153. {
  154. let drop_chance = matches
  155. .opt_str("drop-chance")
  156. .map(|s| u8::from_str(&s).unwrap())
  157. .unwrap_or(0);
  158. let corrupt_chance = matches
  159. .opt_str("corrupt-chance")
  160. .map(|s| u8::from_str(&s).unwrap())
  161. .unwrap_or(0);
  162. let size_limit = matches
  163. .opt_str("size-limit")
  164. .map(|s| usize::from_str(&s).unwrap())
  165. .unwrap_or(0);
  166. let tx_rate_limit = matches
  167. .opt_str("tx-rate-limit")
  168. .map(|s| u64::from_str(&s).unwrap())
  169. .unwrap_or(0);
  170. let rx_rate_limit = matches
  171. .opt_str("rx-rate-limit")
  172. .map(|s| u64::from_str(&s).unwrap())
  173. .unwrap_or(0);
  174. let shaping_interval = matches
  175. .opt_str("shaping-interval")
  176. .map(|s| u64::from_str(&s).unwrap())
  177. .unwrap_or(0);
  178. let pcap_writer: Box<dyn io::Write>;
  179. if let Some(pcap_filename) = matches.opt_str("pcap") {
  180. pcap_writer = Box::new(File::create(pcap_filename).expect("cannot open file"))
  181. } else {
  182. pcap_writer = Box::new(io::sink())
  183. }
  184. let seed = SystemTime::now()
  185. .duration_since(UNIX_EPOCH)
  186. .unwrap()
  187. .subsec_nanos();
  188. let device = PcapWriter::new(
  189. device,
  190. pcap_writer,
  191. if loopback {
  192. PcapMode::TxOnly
  193. } else {
  194. PcapMode::Both
  195. },
  196. );
  197. let device = Tracer::new(device, |_timestamp, _printer| {
  198. #[cfg(feature = "log")]
  199. trace!("{}", _printer);
  200. });
  201. let mut device = FaultInjector::new(device, seed);
  202. device.set_drop_chance(drop_chance);
  203. device.set_corrupt_chance(corrupt_chance);
  204. device.set_max_packet_size(size_limit);
  205. device.set_max_tx_rate(tx_rate_limit);
  206. device.set_max_rx_rate(rx_rate_limit);
  207. device.set_bucket_interval(Duration::from_millis(shaping_interval));
  208. device
  209. }