utils.rs 6.0 KB

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