3
0

MessageMapping.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import os.path
  2. from xml.dom.minidom import *
  3. import datetime
  4. class MessageMapping:
  5. TAG_MAPPING_GROUP = "mappings"
  6. TAG_MAPPING = "mapping"
  7. ATTR_ID = "id"
  8. ATTR_LINENO = "line_number"
  9. ATTR_HAS_PACKET = "mapped"
  10. ATTR_PACKET_TIME = "packet_time"
  11. def __init__(self, messages, pcap_start_timestamp_str):
  12. self.messages = messages
  13. self.id_to_packet = {}
  14. ts_date_format = "%Y-%m-%d %H:%M:%S.%f"
  15. first_msg_dt = datetime.datetime.fromtimestamp(min(messages, key=lambda msg: msg.time).time)
  16. orig_pcap_start_dt = datetime.datetime.strptime(pcap_start_timestamp_str, ts_date_format)
  17. self.pcap_start_dt = min(first_msg_dt, orig_pcap_start_dt)
  18. def map_message(self, message, packet):
  19. self.id_to_packet[message.msg_id] = packet
  20. def to_xml(self, ):
  21. doc = Document()
  22. mappings = doc.createElement(self.TAG_MAPPING_GROUP)
  23. doc.appendChild(mappings)
  24. for message in sorted(self.messages, key=lambda msg: msg.time):
  25. mapping = doc.createElement(self.TAG_MAPPING)
  26. mapping.setAttribute(self.ATTR_ID, str(message.msg_id))
  27. mapping.setAttribute(self.ATTR_LINENO, str(message.line_no))
  28. mapping.setAttribute("Src", str(message.src["ID"]))
  29. mapping.setAttribute("Dst", str(message.dst["ID"]))
  30. mapping.setAttribute("Type", str(message.type.value))
  31. mapping.setAttribute("CSV_XML_Time", str(message.csv_time))
  32. dt = datetime.datetime.fromtimestamp(message.time)
  33. dt_relative = dt - self.pcap_start_dt
  34. mapping.setAttribute("PCAP_Time-Timestamp", str(message.time))
  35. mapping.setAttribute("PCAP_Time-Datetime", dt.strftime("%Y-%m-%d %H:%M:%S.") + str(dt.microsecond))
  36. mapping.setAttribute("PCAP_Time-Relative", "%d.%s" % (dt_relative.total_seconds(), str(dt_relative.microseconds).rjust(6, "0")))
  37. packet = self.id_to_packet.get(message.msg_id)
  38. mapping.setAttribute(self.ATTR_HAS_PACKET, "true" if packet is not None else "false")
  39. if packet:
  40. mapping.setAttribute(self.ATTR_PACKET_TIME, str(packet.time))
  41. mappings.appendChild(mapping)
  42. return doc
  43. def write_to(self, buffer, close = True):
  44. buffer.write(self.to_xml().toprettyxml())
  45. if close: buffer.close()
  46. def write_to_file(self, filename: str, *args, **kwargs):
  47. self.write_to(open(filename, "w", *args, **kwargs))
  48. def write_next_to_pcap_file(self, pcap_filename : str, mapping_ext = "_mapping.xml", *args, **kwargs):
  49. pcap_base = os.path.splitext(pcap_filename)[0]
  50. self.write_to_file(pcap_base + mapping_ext, *args, **kwargs)