MessageMapping.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import os.path
  2. from xml.dom.minidom import *
  3. class MessageMapping:
  4. TAG_MAPPING_GROUP = "mappings"
  5. TAG_MAPPING = "mapping"
  6. ATTR_ID = "id"
  7. ATTR_LINENO = "line_number"
  8. ATTR_HAS_PACKET = "mapped"
  9. ATTR_PACKET_TIME = "packet_time"
  10. def __init__(self, messages):
  11. self.messages = messages
  12. self.id_to_packet = {}
  13. def map_message(self, message, packet):
  14. self.id_to_packet[message.msg_id] = packet
  15. def to_xml(self):
  16. doc = Document()
  17. mappings = doc.createElement(self.TAG_MAPPING_GROUP)
  18. doc.appendChild(mappings)
  19. for message in self.messages:
  20. mapping = doc.createElement(self.TAG_MAPPING)
  21. mapping.setAttribute(self.ATTR_ID, str(message.msg_id))
  22. mapping.setAttribute(self.ATTR_LINENO, str(message.line_no))
  23. mapping.setAttribute("Src", str(message.src["ID"]))
  24. mapping.setAttribute("Dst", str(message.dst["ID"]))
  25. mapping.setAttribute("Type", str(message.type.value))
  26. mapping.setAttribute("Time", str(message.time))
  27. packet = self.id_to_packet.get(message.msg_id)
  28. mapping.setAttribute(self.ATTR_HAS_PACKET, "true" if packet is not None else "false")
  29. if packet:
  30. mapping.setAttribute(self.ATTR_PACKET_TIME, str(packet.time))
  31. mappings.appendChild(mapping)
  32. return doc
  33. def write_to(self, buffer, close = True):
  34. buffer.write(self.to_xml().toprettyxml())
  35. if close: buffer.close()
  36. def write_to_file(self, filename: str, *args, **kwargs):
  37. self.write_to(open(filename, "w", *args, **kwargs))
  38. def write_next_to_pcap_file(self, pcap_filename : str, mapping_ext = "_mapping.xml", *args, **kwargs):
  39. pcap_base = os.path.splitext(pcap_filename)[0]
  40. self.write_to_file(pcap_base + mapping_ext, *args, **kwargs)