utils.rs 4.4 KB

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