utils.rs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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. pub fn create_options() -> (Options, Vec<&'static str>) {
  47. let mut opts = Options::new();
  48. opts.optflag("h", "help", "print this help menu");
  49. (opts, Vec::new())
  50. }
  51. pub fn parse_options(options: &Options, free: Vec<&str>) -> Matches {
  52. match options.parse(env::args().skip(1)) {
  53. Err(err) => {
  54. println!("{}", err);
  55. process::exit(1)
  56. }
  57. Ok(matches) => {
  58. if matches.opt_present("h") || matches.free.len() != free.len() {
  59. let brief = format!("Usage: {} [OPTION]... {}",
  60. env::args().nth(0).unwrap(), free.join(" "));
  61. print!("{}", options.usage(&brief));
  62. process::exit(if matches.free.len() != free.len() { 1 } else { 0 })
  63. }
  64. matches
  65. }
  66. }
  67. }
  68. pub fn add_tap_options(_opts: &mut Options, free: &mut Vec<&str>) {
  69. free.push("INTERFACE");
  70. }
  71. pub fn parse_tap_options(matches: &mut Matches) -> TapInterface {
  72. let interface = matches.free.remove(0);
  73. TapInterface::new(&interface).unwrap()
  74. }
  75. pub fn add_middleware_options(opts: &mut Options, _free: &mut Vec<&str>) {
  76. opts.optopt("", "pcap", "Write a packet capture file", "FILE");
  77. opts.optopt("", "drop-chance", "Chance of dropping a packet (%)", "CHANCE");
  78. opts.optopt("", "corrupt-chance", "Chance of corrupting a packet (%)", "CHANCE");
  79. opts.optopt("", "size-limit", "Drop packets larger than given size (octets)", "SIZE");
  80. opts.optopt("", "tx-rate-limit", "Drop packets after transmit rate exceeds given limit \
  81. (packets per interval)", "RATE");
  82. opts.optopt("", "rx-rate-limit", "Drop packets after transmit rate exceeds given limit \
  83. (packets per interval)", "RATE");
  84. opts.optopt("", "shaping-interval", "Sets the interval for rate limiting (ms)", "RATE");
  85. }
  86. pub fn parse_middleware_options<D: Device>(matches: &mut Matches, device: D, loopback: bool)
  87. -> FaultInjector<EthernetTracer<PcapWriter<D, Rc<PcapSink>>>> {
  88. let drop_chance = matches.opt_str("drop-chance").map(|s| u8::from_str(&s).unwrap())
  89. .unwrap_or(0);
  90. let corrupt_chance = matches.opt_str("corrupt-chance").map(|s| u8::from_str(&s).unwrap())
  91. .unwrap_or(0);
  92. let size_limit = matches.opt_str("size-limit").map(|s| usize::from_str(&s).unwrap())
  93. .unwrap_or(0);
  94. let tx_rate_limit = matches.opt_str("tx-rate-limit").map(|s| u64::from_str(&s).unwrap())
  95. .unwrap_or(0);
  96. let rx_rate_limit = matches.opt_str("rx-rate-limit").map(|s| u64::from_str(&s).unwrap())
  97. .unwrap_or(0);
  98. let shaping_interval = matches.opt_str("shaping-interval").map(|s| u64::from_str(&s).unwrap())
  99. .unwrap_or(0);
  100. let pcap_writer: Box<io::Write>;
  101. if let Some(pcap_filename) = matches.opt_str("pcap") {
  102. pcap_writer = Box::new(File::create(pcap_filename).expect("cannot open file"))
  103. } else {
  104. pcap_writer = Box::new(io::sink())
  105. }
  106. let seed = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().subsec_nanos();
  107. let device = PcapWriter::new(device, Rc::new(RefCell::new(pcap_writer)) as Rc<PcapSink>,
  108. if loopback { PcapMode::TxOnly } else { PcapMode::Both },
  109. PcapLinkType::Ethernet);
  110. let device = EthernetTracer::new(device, |_timestamp, printer| trace!("{}", printer));
  111. let mut device = FaultInjector::new(device, seed);
  112. device.set_drop_chance(drop_chance);
  113. device.set_corrupt_chance(corrupt_chance);
  114. device.set_max_packet_size(size_limit);
  115. device.set_max_tx_rate(tx_rate_limit);
  116. device.set_max_rx_rate(rx_rate_limit);
  117. device.set_bucket_interval(shaping_interval);
  118. device
  119. }
  120. pub fn millis_since(startup_time: Instant) -> u64 {
  121. let duration = Instant::now().duration_since(startup_time);
  122. let duration_ms = (duration.as_secs() * 1000) +
  123. (duration.subsec_nanos() / 1000000) as u64;
  124. duration_ms
  125. }