MessageMapping.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. self.pcap_start_dt = datetime.datetime.strptime(pcap_start_timestamp_str, ts_date_format)
  16. def map_message(self, message, packet):
  17. self.id_to_packet[message.msg_id] = packet
  18. def to_xml(self, ):
  19. doc = Document()
  20. mappings = doc.createElement(self.TAG_MAPPING_GROUP)
  21. doc.appendChild(mappings)
  22. for message in self.messages:
  23. mapping = doc.createElement(self.TAG_MAPPING)
  24. mapping.setAttribute(self.ATTR_ID, str(message.msg_id))
  25. mapping.setAttribute(self.ATTR_LINENO, str(message.line_no))
  26. mapping.setAttribute("Src", str(message.src["ID"]))
  27. mapping.setAttribute("Dst", str(message.dst["ID"]))
  28. mapping.setAttribute("Type", str(message.type.value))
  29. mapping.setAttribute("CSV_XML_Time", str(message.csv_time))
  30. dt = datetime.datetime.fromtimestamp(message.time)
  31. dt_relative = dt - self.pcap_start_dt
  32. mapping.setAttribute("PCAP_Time-Timestamp", str(message.time))
  33. mapping.setAttribute("PCAP_Time-Datetime", dt.strftime("%Y-%m-%d %H:%M:%S.") + str(dt.microsecond))
  34. mapping.setAttribute("PCAP_Time-Relative", "%d.%s" % (dt_relative.total_seconds(), str(dt_relative.microseconds).rjust(6, "0")))
  35. packet = self.id_to_packet.get(message.msg_id)
  36. mapping.setAttribute(self.ATTR_HAS_PACKET, "true" if packet is not None else "false")
  37. if packet:
  38. mapping.setAttribute(self.ATTR_PACKET_TIME, str(packet.time))
  39. mappings.appendChild(mapping)
  40. return doc
  41. def write_to(self, buffer, close = True):
  42. buffer.write(self.to_xml().toprettyxml())
  43. if close: buffer.close()
  44. def write_to_file(self, filename: str, *args, **kwargs):
  45. self.write_to(open(filename, "w", *args, **kwargs))
  46. def write_next_to_pcap_file(self, pcap_filename : str, mapping_ext = "_mapping.xml", *args, **kwargs):
  47. pcap_base = os.path.splitext(pcap_filename)[0]
  48. self.write_to_file(pcap_base + mapping_ext, *args, **kwargs)