utils.rs 6.2 KB

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