utils.rs 6.8 KB

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