utils.rs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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::{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};
  16. #[cfg(feature = "phy-tap_interface")]
  17. use smoltcp::phy::TapInterface;
  18. use smoltcp::phy::{PcapWriter, PcapSink, PcapMode, PcapLinkType};
  19. use smoltcp::time::{Duration, Instant};
  20. #[cfg(feature = "log")]
  21. pub fn setup_logging_with_clock<F>(filter: &str, since_startup: F)
  22. where F: Fn() -> Instant + Send + Sync + 'static {
  23. LogBuilder::new()
  24. .format(move |record: &LogRecord| {
  25. let elapsed = since_startup();
  26. let timestamp = format!("[{}]", elapsed);
  27. if record.target().starts_with("smoltcp::") {
  28. format!("\x1b[0m{} ({}): {}\x1b[0m", timestamp,
  29. record.target().replace("smoltcp::", ""), record.args())
  30. } else if record.level() == LogLevel::Trace {
  31. let message = format!("{}", record.args());
  32. format!("\x1b[37m{} {}\x1b[0m", timestamp,
  33. message.replace("\n", "\n "))
  34. } else {
  35. format!("\x1b[32m{} ({}): {}\x1b[0m", timestamp,
  36. record.target(), record.args())
  37. }
  38. })
  39. .filter(None, LogLevelFilter::Trace)
  40. .parse(filter)
  41. .parse(&env::var("RUST_LOG").unwrap_or("".to_owned()))
  42. .init()
  43. .unwrap();
  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().nth(0).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_tap_options(_opts: &mut Options, free: &mut Vec<&str>) {
  74. free.push("INTERFACE");
  75. }
  76. #[cfg(feature = "phy-tap_interface")]
  77. pub fn parse_tap_options(matches: &mut Matches) -> TapInterface {
  78. let interface = matches.free.remove(0);
  79. TapInterface::new(&interface).unwrap()
  80. }
  81. pub fn add_middleware_options(opts: &mut Options, _free: &mut Vec<&str>) {
  82. opts.optopt("", "pcap", "Write a packet capture file", "FILE");
  83. opts.optopt("", "drop-chance", "Chance of dropping a packet (%)", "CHANCE");
  84. opts.optopt("", "corrupt-chance", "Chance of corrupting a packet (%)", "CHANCE");
  85. opts.optopt("", "size-limit", "Drop packets larger than given size (octets)", "SIZE");
  86. opts.optopt("", "tx-rate-limit", "Drop packets after transmit rate exceeds given limit \
  87. (packets per interval)", "RATE");
  88. opts.optopt("", "rx-rate-limit", "Drop packets after transmit rate exceeds given limit \
  89. (packets per interval)", "RATE");
  90. opts.optopt("", "shaping-interval", "Sets the interval for rate limiting (ms)", "RATE");
  91. }
  92. pub fn parse_middleware_options<D>(matches: &mut Matches, device: D, loopback: bool)
  93. -> FaultInjector<EthernetTracer<PcapWriter<D, Rc<PcapSink>>>>
  94. where D: for<'a> Device<'a>
  95. {
  96. let drop_chance = matches.opt_str("drop-chance").map(|s| u8::from_str(&s).unwrap())
  97. .unwrap_or(0);
  98. let corrupt_chance = matches.opt_str("corrupt-chance").map(|s| u8::from_str(&s).unwrap())
  99. .unwrap_or(0);
  100. let size_limit = matches.opt_str("size-limit").map(|s| usize::from_str(&s).unwrap())
  101. .unwrap_or(0);
  102. let tx_rate_limit = matches.opt_str("tx-rate-limit").map(|s| u64::from_str(&s).unwrap())
  103. .unwrap_or(0);
  104. let rx_rate_limit = matches.opt_str("rx-rate-limit").map(|s| u64::from_str(&s).unwrap())
  105. .unwrap_or(0);
  106. let shaping_interval = matches.opt_str("shaping-interval").map(|s| u64::from_str(&s).unwrap())
  107. .unwrap_or(0);
  108. let pcap_writer: Box<io::Write>;
  109. if let Some(pcap_filename) = matches.opt_str("pcap") {
  110. pcap_writer = Box::new(File::create(pcap_filename).expect("cannot open file"))
  111. } else {
  112. pcap_writer = Box::new(io::sink())
  113. }
  114. let seed = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().subsec_nanos();
  115. let device = PcapWriter::new(device, Rc::new(RefCell::new(pcap_writer)) as Rc<PcapSink>,
  116. if loopback { PcapMode::TxOnly } else { PcapMode::Both },
  117. PcapLinkType::Ethernet);
  118. let device = EthernetTracer::new(device, |_timestamp, _printer| {
  119. #[cfg(feature = "log")]
  120. trace!("{}", _printer);
  121. });
  122. let mut device = FaultInjector::new(device, seed);
  123. device.set_drop_chance(drop_chance);
  124. device.set_corrupt_chance(corrupt_chance);
  125. device.set_max_packet_size(size_limit);
  126. device.set_max_tx_rate(tx_rate_limit);
  127. device.set_max_rx_rate(rx_rate_limit);
  128. device.set_bucket_interval(Duration::from_millis(shaping_interval));
  129. device
  130. }