packet2pcap.rs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. extern crate smoltcp;
  2. extern crate getopts;
  3. use std::cell::RefCell;
  4. use std::io::{self, Read, Write};
  5. use std::path::Path;
  6. use std::fs::File;
  7. use std::env;
  8. use std::process::exit;
  9. use smoltcp::phy::{PcapLinkType, PcapSink};
  10. use getopts::Options;
  11. fn convert(packet_filename: &Path, pcap_filename: &Path, link_type: PcapLinkType)
  12. -> io::Result<()> {
  13. let mut packet_file = File::open(packet_filename)?;
  14. let mut packet = Vec::new();
  15. packet_file.read_to_end(&mut packet)?;
  16. let pcap = RefCell::new(Vec::new());
  17. PcapSink::global_header(&pcap, link_type);
  18. PcapSink::packet(&pcap, 0, &packet[..]);
  19. let mut pcap_file = File::create(pcap_filename)?;
  20. pcap_file.write_all(&pcap.borrow()[..])?;
  21. Ok(())
  22. }
  23. fn print_usage(program: &str, opts: Options) {
  24. let brief = format!("Usage: {} [options] INPUT OUTPUT", program);
  25. print!("{}", opts.usage(&brief));
  26. }
  27. fn main() {
  28. let args: Vec<String> = env::args().collect();
  29. let program = args[0].clone();
  30. let mut opts = Options::new();
  31. opts.optflag("h", "help", "print this help menu");
  32. opts.optopt("t", "link-type", "set link type (one of: ethernet ip)", "TYPE");
  33. let matches = match opts.parse(&args[1..]) {
  34. Ok(m) => m,
  35. Err(e) => {
  36. eprintln!("{}", e);
  37. return
  38. }
  39. };
  40. let link_type =
  41. match matches.opt_str("t").as_ref().map(|s| &s[..]) {
  42. Some("ethernet") => Some(PcapLinkType::Ethernet),
  43. Some("ip") => Some(PcapLinkType::Ip),
  44. _ => None
  45. };
  46. if matches.opt_present("h") || matches.free.len() != 2 || link_type.is_none() {
  47. print_usage(&program, opts);
  48. return
  49. }
  50. match convert(Path::new(&matches.free[0]),
  51. Path::new(&matches.free[1]),
  52. link_type.unwrap()) {
  53. Ok(()) => (),
  54. Err(e) => {
  55. eprintln!("Cannot convert packet to pcap: {}", e);
  56. exit(1);
  57. }
  58. }
  59. }