MessageMapping.py 2.1 KB

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