ntp.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """Network Time Protocol."""
  2. from pypacker import pypacker
  3. import logging
  4. logger = logging.getLogger("pypacker")
  5. # NTP v4
  6. # Leap Indicator (LI) Codes
  7. NO_WARNING = 0
  8. LAST_MINUTE_61_SECONDS = 1
  9. LAST_MINUTE_59_SECONDS = 2
  10. ALARM_CONDITION = 3
  11. # Mode Codes
  12. RESERVED = 0
  13. SYMMETRIC_ACTIVE = 1
  14. SYMMETRIC_PASSIVE = 2
  15. CLIENT = 3
  16. SERVER = 4
  17. BROADCAST = 5
  18. CONTROL_MESSAGE = 6
  19. PRIVATE = 7
  20. class NTP(pypacker.Packet):
  21. __hdr__ = (
  22. ("flags", "B", 0x1c), # li | v | mode
  23. ("stratum", "B", 0x2),
  24. ("interval", "B", 0x4),
  25. ("precision", "B", 0xe9),
  26. ("delay", "I", 0),
  27. ("dispersion", "I", 0),
  28. ("id", "4s", b"\x00\x01\x02\x03"),
  29. # timestamps: [seconds since 1.1.1900 | fraction of seconds]
  30. ("update_time", "8s", b"\x00" * 8),
  31. ("originate_time", "8s", b"" * 8),
  32. ("receive_time", "8s", b"" * 8),
  33. ("transmit_time", "8s", b"" * 8)
  34. )
  35. """
  36. [xx][xx x][xxx]
  37. li v mode
  38. __m_switch_set = {"v":lambda flags,v: (flags & ~0x38) | ((v & 0x7) << 3),
  39. "li":lambda flags,li: (flags & ~0xc0) | ((li & 0x3) << 6),
  40. "mode":lambda flags,mode: (flags & ~0x7) | (mode & 0x7)
  41. }
  42. __m_switch_get = {"v":lambda flags: (flags >> 3) & 0x7,
  43. "li":lambda flags: (flags >> 6) & 0x3,
  44. "mode":lambda flags: (flags & 0x7)
  45. }
  46. """
  47. def __get_v(self):
  48. return (self.flags >> 3) & 0x7
  49. def __set_v(self, value):
  50. self.flags = (self.flags & ~0x38) | ((value & 0x7) << 3)
  51. v = property(__get_v, __set_v)
  52. def __get_li(self):
  53. return (self.flags >> 6) & 0x3
  54. def __set_li(self, value):
  55. self.flags = (self.flags & ~0xc0) | ((value & 0x3) << 6)
  56. li = property(__get_li, __set_li)
  57. def __get_mode(self):
  58. return self.flags & 0x7
  59. def __set_mode(self, value):
  60. self.flags = (self.flags & ~0x7) | (value & 0x7)
  61. mode = property(__get_mode, __set_mode)