MessageMapping.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. packet = self.id_to_packet.get(message.msg_id)
  24. mapping.setAttribute(self.ATTR_HAS_PACKET, "true" if packet is not None else "false")
  25. if packet:
  26. mapping.setAttribute(self.ATTR_PACKET_TIME, str(packet.time))
  27. mappings.appendChild(mapping)
  28. return doc
  29. def write_to(self, buffer, close = True):
  30. buffer.write(self.to_xml().toprettyxml())
  31. if close: buffer.close()
  32. def write_to_file(self, filename: str, *args, **kwargs):
  33. self.write_to(open(filename, "w", *args, **kwargs))
  34. def write_next_to_pcap_file(self, pcap_filename : str, mapping_ext = "_mapping.xml", *args, **kwargs):
  35. pcap_base = os.path.splitext(pcap_filename)[0]
  36. self.write_to_file(pcap_base + mapping_ext, *args, **kwargs)