PcapFile.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2014 Dolphin Emulator Project
  2. // Licensed under GPLv2+
  3. // Refer to the license.txt file included.
  4. #include <chrono>
  5. #include "Common/CommonTypes.h"
  6. #include "Common/FileUtil.h"
  7. #include "Common/PcapFile.h"
  8. namespace {
  9. const u32 PCAP_MAGIC = 0xa1b2c3d4;
  10. const u16 PCAP_VERSION_MAJOR = 2;
  11. const u16 PCAP_VERSION_MINOR = 4;
  12. const u32 PCAP_CAPTURE_LENGTH = 65535;
  13. // TODO(delroth): Make this configurable at PCAP creation time?
  14. const u32 PCAP_DATA_LINK_TYPE = 147; // Reserved for internal use.
  15. // Designed to be directly written into the PCAP file. The PCAP format is
  16. // endian independent, so this works just fine.
  17. #pragma pack(push, 1)
  18. struct PCAPHeader
  19. {
  20. u32 magic_number;
  21. u16 version_major;
  22. u16 version_minor;
  23. s32 tz_offset; // Offset in seconds from the GMT timezone.
  24. u32 ts_accuracy; // In practice, 0.
  25. u32 capture_length; // Size at which we truncate packets.
  26. u32 data_link_type;
  27. };
  28. struct PCAPRecordHeader
  29. {
  30. u32 ts_sec;
  31. u32 ts_usec;
  32. u32 size_in_file; // Size after eventual truncation.
  33. u32 real_size; // Size before eventual truncation.
  34. };
  35. #pragma pack(pop)
  36. } // namespace
  37. void PCAP::AddHeader()
  38. {
  39. PCAPHeader hdr = {
  40. PCAP_MAGIC, PCAP_VERSION_MAJOR, PCAP_VERSION_MINOR,
  41. 0, 0, PCAP_CAPTURE_LENGTH, PCAP_DATA_LINK_TYPE
  42. };
  43. m_fp->WriteBytes(&hdr, sizeof (hdr));
  44. }
  45. void PCAP::AddPacket(const u8* bytes, size_t size)
  46. {
  47. std::chrono::system_clock::time_point now(std::chrono::system_clock::now());
  48. auto ts = now.time_since_epoch();
  49. PCAPRecordHeader rec_hdr = {
  50. (u32)std::chrono::duration_cast<std::chrono::seconds>(ts).count(),
  51. (u32)(std::chrono::duration_cast<std::chrono::microseconds>(ts).count() % 1000000),
  52. (u32)size, (u32)size
  53. };
  54. m_fp->WriteBytes(&rec_hdr, sizeof (rec_hdr));
  55. m_fp->WriteBytes(bytes, size);
  56. }