utils.rs 5.8 KB

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