utils.rs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. use std::str::{self, FromStr};
  2. use std::env;
  3. use std::time::{Instant, Duration, SystemTime, UNIX_EPOCH};
  4. use std::process;
  5. use log::{LogLevelFilter, LogRecord};
  6. use env_logger::{LogBuilder};
  7. use getopts;
  8. use smoltcp::phy::{Tracer, FaultInjector, TapInterface};
  9. use smoltcp::wire::EthernetFrame;
  10. use smoltcp::wire::PrettyPrinter;
  11. pub fn setup_logging() {
  12. let startup_time = Instant::now();
  13. LogBuilder::new()
  14. .format(move |record: &LogRecord| {
  15. let elapsed = Instant::now().duration_since(startup_time);
  16. let timestamp = format!("[{:6}.{:03}s]",
  17. elapsed.as_secs(), elapsed.subsec_nanos() / 1000000);
  18. if record.target().ends_with("::utils") {
  19. let mut message = format!("{}", record.args());
  20. message.pop();
  21. format!("\x1b[37m{} {}\x1b[0m", timestamp,
  22. message.replace("\n", "\n "))
  23. } else if record.target().starts_with("smoltcp::") {
  24. format!("\x1b[0m{} ({}): {}\x1b[0m", timestamp,
  25. record.target().replace("smoltcp::", ""), record.args())
  26. } else {
  27. format!("\x1b[32m{} ({}): {}\x1b[0m", timestamp,
  28. record.target(), record.args())
  29. }
  30. })
  31. .filter(None, LogLevelFilter::Trace)
  32. .init()
  33. .unwrap();
  34. }
  35. pub fn setup_device(more_args: &[&str])
  36. -> (Tracer<FaultInjector<TapInterface>, EthernetFrame<&'static [u8]>>,
  37. Vec<String>) {
  38. let mut opts = getopts::Options::new();
  39. opts.optopt("", "drop-chance", "Chance of dropping a packet (%)", "CHANCE");
  40. opts.optopt("", "corrupt-chance", "Chance of corrupting a packet (%)", "CHANCE");
  41. opts.optopt("", "size-limit", "Drop packets larger than given size (octets)", "SIZE");
  42. opts.optopt("", "tx-rate-limit", "Drop packets after transmit rate exceeds given limit \
  43. (packets per interval)", "RATE");
  44. opts.optopt("", "rx-rate-limit", "Drop packets after transmit rate exceeds given limit \
  45. (packets per interval)", "RATE");
  46. opts.optopt("", "shaping-interval", "Sets the interval for rate limiting (ms)", "RATE");
  47. opts.optflag("h", "help", "print this help menu");
  48. let matches = opts.parse(env::args().skip(1)).unwrap();
  49. if matches.opt_present("h") || matches.free.len() != more_args.len() + 1 {
  50. let brief = format!("Usage: {} INTERFACE {} [options]",
  51. env::args().nth(0).unwrap(),
  52. more_args.join(" "));
  53. print!("{}", opts.usage(&brief));
  54. process::exit(if matches.free.len() != more_args.len() + 1 { 1 } else { 0 });
  55. }
  56. let drop_chance = u8::from_str(&matches.opt_str("drop-chance")
  57. .unwrap_or("0".to_string())).unwrap();
  58. let corrupt_chance = u8::from_str(&matches.opt_str("corrupt-chance")
  59. .unwrap_or("0".to_string())).unwrap();
  60. let size_limit = usize::from_str(&matches.opt_str("size-limit")
  61. .unwrap_or("0".to_string())).unwrap();
  62. let tx_rate_limit = u64::from_str(&matches.opt_str("tx-rate-limit")
  63. .unwrap_or("0".to_string())).unwrap();
  64. let rx_rate_limit = u64::from_str(&matches.opt_str("rx-rate-limit")
  65. .unwrap_or("0".to_string())).unwrap();
  66. let shaping_interval = u32::from_str(&matches.opt_str("shaping-interval")
  67. .unwrap_or("0".to_string())).unwrap();
  68. let seed = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().subsec_nanos();
  69. fn trace_writer(printer: PrettyPrinter<EthernetFrame<&[u8]>>) {
  70. trace!("{}", printer)
  71. }
  72. let device = TapInterface::new(&matches.free[0]).unwrap();
  73. let mut device = FaultInjector::new(device, seed);
  74. device.set_drop_chance(drop_chance);
  75. device.set_corrupt_chance(corrupt_chance);
  76. device.set_max_packet_size(size_limit);
  77. device.set_max_tx_rate(tx_rate_limit);
  78. device.set_max_rx_rate(rx_rate_limit);
  79. device.set_bucket_interval(Duration::from_millis(shaping_interval as u64));
  80. let device = Tracer::<_, EthernetFrame<&'static [u8]>>::new(device, trace_writer);
  81. (device, matches.free[1..].to_owned())
  82. }