-
Notifications
You must be signed in to change notification settings - Fork 4
/
ntplib.py
305 lines (248 loc) · 9.91 KB
/
ntplib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
###############################################################################
# ntplib - Python NTP library.
# Copyright (C) 2009 Charles-Francois Natali <neologix@free.fr>
#
# ntplib is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 0.1.2-1307 USA
###############################################################################
'''Pyton NTP library.
Implementation of client-side NTP (RFC-1305), and useful NTP-related
functions.
'''
import socket
import struct
import time
import datetime
# compute delta between system epoch and NTP epoch
SYSTEM_EPOCH = datetime.date(*time.gmtime(0)[0:3])
NTP_EPOCH = datetime.date(1900, 1, 1)
NTP_DELTA = (SYSTEM_EPOCH - NTP_EPOCH).days * 24 * 3600
class NTPException(Exception):
"""Exception raised by this module."""
class NTPPacket(object):
"""NTP packet class.
This class abstracts the stucture of a NTP packet."""
# packet format to pack/unpack
ntp_packet_format = '!B B B b 11I'
def __init__(self, version=2, mode=3, tx_timestamp=0):
self.leap = 0
self.version = version
self.mode = mode
self.stratum = 0
self.poll = 0
self.precision = 0
self.root_delay = 0
self.root_dispersion = 0
self.ref_id = 0
self.ref_timestamp = 0
self.orig_timestamp = 0
self.recv_timestamp = 0
self.tx_timestamp = tx_timestamp
def to_data(self):
"""convert a NTPPacket to a NTP packet that can be sent over network
raise a NTPException in case of invalid field"""
try:
packed = struct.pack(NTPPacket.ntp_packet_format,
(self.leap << 6 | self.version << 3 | self.mode),
self.stratum,
self.poll,
self.precision,
to_int(self.root_delay) << 16 | to_frac(self.root_delay, 16),
to_int(self.root_dispersion) << 16 |
to_frac(self.root_dispersion, 16),
self.ref_id,
to_int(self.ref_timestamp),
to_frac(self.ref_timestamp),
to_int(self.orig_timestamp),
to_frac(self.orig_timestamp),
to_int(self.recv_timestamp),
to_frac(self.recv_timestamp),
to_int(self.tx_timestamp),
to_frac(self.tx_timestamp))
except struct.error:
raise NTPException('Invalid packet fields')
return packed
def from_data(self, data):
"""build a NTPPacket from a NTP packet received from network
raise an NTPException in case of invalid packet format"""
if len(data) != struct.calcsize(NTPPacket.ntp_packet_format):
raise NTPException('Incorrect NTP packet header size')
unpacked = struct.unpack(NTPPacket.ntp_packet_format, data)
self.leap = unpacked[0] >> 6 & 0x3
self.version = unpacked[0] >> 3 & 0x7
self.mode = unpacked[0] & 0x7
self.stratum = unpacked[1]
self.poll = unpacked[2]
self.precision = unpacked[3]
self.root_delay = float(unpacked[4])/2**16
self.root_dispersion = float(unpacked[5])/2**16
self.ref_id = unpacked[6]
self.ref_timestamp = to_time(unpacked[7], unpacked[8])
self.orig_timestamp = to_time(unpacked[9], unpacked[10])
self.recv_timestamp = to_time(unpacked[11], unpacked[12])
self.tx_timestamp = to_time(unpacked[13], unpacked[14])
class NTPStats(NTPPacket):
"""wrapper for NTPPacket, offering additional statistics like offset and
delay, and timestamps converted to local time"""
def __init__(self, dest_timestamp):
NTPPacket.__init__(self)
self.dest_timestamp = dest_timestamp
@property
def offset(self):
"""NTP offset"""
return ((self.recv_timestamp - self.orig_timestamp) +
(self.tx_timestamp - self.dest_timestamp))/2
@property
def delay(self):
"""NTP delay"""
return ((self.dest_timestamp - self.orig_timestamp) -
(self.recv_timestamp - self.tx_timestamp))
@property
def tx_time(self):
"""tx_timestamp - local time"""
return ntp_to_system_time(self.tx_timestamp)
@property
def recv_time(self):
"""recv_timestamp - local time"""
return ntp_to_system_time(self.recv_timestamp)
@property
def orig_time(self):
"""orig_timestamp - local time"""
return ntp_to_system_time(self.orig_timestamp)
@property
def ref_time(self):
"""ref_timestamp - local time"""
return ntp_to_system_time(self.ref_timestamp)
@property
def dest_time(self):
"""dest_timestamp - local time"""
return ntp_to_system_time(self.dest_timestamp)
class NTPClient(object):
"""Client session - for now, a mere wrapper for NTP requests"""
def request(self, host, version=2, port='ntp'):
"""make a NTP request to a server - return a NTPStats object
raise a NTPException if the server doesn't respond within a reasonable
interval"""
# create the socket - let the application handle (unlikely) exceptions
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(15)
try:
# lookup server address
sockaddr = socket.getaddrinfo(host, port)[0][4]
# create the request packet - mode 3 is client
query = NTPPacket(mode=3, version=version,
tx_timestamp=system_to_ntp_time(time.time()))
query_packet = query.to_data()
# send the request
s.sendto(query_packet, sockaddr)
# wait for the response - check the source address
src_addr = (None, None)
while src_addr != sockaddr:
(response_packet, src_addr) = s.recvfrom(len(query_packet))
# build the destination timestamp
dest_timestamp = system_to_ntp_time(time.time())
except socket.timeout:
raise NTPException('No response from server')
finally:
# no matter what happens, we must close the socket
# if an exception was raised, let the application hanle it
s.close()
# construct corresponding statistics
response = NTPStats(dest_timestamp)
response.from_data(response_packet)
return response
def to_int(date):
"""return the integral part of a timestamp"""
return int(date)
def to_frac(date, n=32):
"""return the fractional part of a timestamp - n is the number of bits of
the fractional part"""
return int(abs(date - to_int(date)) * 2**n)
def to_time(integ, frac, n=32):
"""build a timestamp from an integral and fractional part - n is the
number of bits of the fractional part"""
return integ + float(frac)/2**n
def ntp_to_system_time(date):
"""convert a NTP time to system time"""
return date - NTP_DELTA
def system_to_ntp_time(date):
"""convert a system time to a NTP time"""
return date + NTP_DELTA
def leap_to_text(leap):
"""convert a leap value to text"""
leap_table = {
0: 'no warning',
1: 'last minute has 61 seconds',
2: 'last minute has 59 seconds',
3: 'alarm condition (clock not synchronized)',
}
if leap in leap_table:
return leap_table[leap]
else:
raise NTPException('Invalid leap indicator')
def mode_to_text(mode):
"""convert a mode value to text"""
mode_table = {
0: 'unspecified',
1: 'symmetric active',
2: 'symmetric passive',
3: 'client',
4: 'server',
5: 'broadcast',
6: 'reserved for NTP control messages',
7: 'reserved for private use',
}
if mode in mode_table:
return mode_table[mode]
else:
raise NTPException('Invalid mode')
def stratum_to_text(stratum):
"""convert a stratum value to text"""
stratum_table = {
0: 'unspecified',
1: 'primary reference',
}
if stratum in stratum_table:
return stratum_table[stratum]
elif 1 < stratum < 255:
return 'secondary reference (NTP)'
else:
raise NTPException('Invalid stratum')
def ref_id_to_text(ref_id, stratum=2):
"""convert a reference identifier to text according to stratum"""
ref_id_table = {
'DNC': 'DNC routing protocol',
'NIST': 'NIST public modem',
'TSP': 'TSP time protocol',
'DTS': 'Digital Time Service',
'ATOM': 'Atomic clock (calibrated)',
'VLF': 'VLF radio (OMEGA, etc)',
'callsign': 'Generic radio',
'LORC': 'LORAN-C radionavidation',
'GOES': 'GOES UHF environment satellite',
'GPS': 'GPS UHF satellite positioning',
}
fields = (ref_id >> 24 & 0xff, ref_id >> 16 & 0xff,
ref_id >> 8 & 0xff, ref_id & 0xff)
# return the result as a string or dot-formatted IP address
if 0 <= stratum <= 1 :
text = '%c%c%c%c' % fields
if text in ref_id_table:
return ref_id_table[text]
else:
return text
elif 2 <= stratum < 255:
return '%d.%d.%d.%d' % fields
else:
raise NTPException('Invalid reference clock identifier')