-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
472 lines (433 loc) · 12.6 KB
/
main.go
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
package main
import (
"encoding/binary"
"fmt"
"log"
"math"
"net"
"os"
"strconv"
"strings"
"time"
"github.com/lxn/walk"
. "github.com/lxn/walk/declarative"
)
const WINDOW_TITLE = "simple-ntp"
const NTP_PORT = 123
const NTP_TIMEOUT = 10
const UNIX_TIME_OFFSET = 2208988800
type MyMainWindow struct {
*walk.MainWindow
hostUrl *walk.LineEdit
portNumber *walk.NumberEdit
timeout *walk.NumberEdit
ipv4Display *walk.CheckBox
msDisplay *walk.CheckBox
leapIndicator *walk.LineEdit
versionNumber *walk.LineEdit
mode *walk.LineEdit
stratum *walk.LineEdit
pollInterval *walk.LineEdit
precision *walk.LineEdit
rootDelay *walk.LineEdit
rootDispersion *walk.LineEdit
referenceID *walk.LineEdit
referenceTimestamp *walk.LineEdit
originTimestamp *walk.LineEdit
receiveTimestamp *walk.LineEdit
transmitTimestamp *walk.LineEdit
}
func reqNtp(host string, port int, timeout int) ([]byte, error) {
ntpQuery := make([]byte, 48)
ntpQuery[0] = 0x1b
s, err := net.Dial("udp", fmt.Sprintf("%s:%d", host, port))
if err != nil {
return ntpQuery, err
}
defer s.Close()
s.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second))
_, err = s.Write(ntpQuery)
if err != nil {
return ntpQuery, err
}
_, err = s.Read(ntpQuery)
if err != nil {
return ntpQuery, err
}
return ntpQuery, err
}
func desc(number int, describe string) string {
return strconv.Itoa(number) + " (" + describe + ")"
}
func parseNtpShortFormat(t []byte) float64 {
s := float64(binary.BigEndian.Uint16(t[0:2]))
f := float64(binary.BigEndian.Uint16(t[2:4])) * math.Pow(2, -16)
return s + f
}
func parseNtpTimestampFormat(t []byte) float64 {
s := float64(binary.BigEndian.Uint32(t[0:4]))
f := float64(binary.BigEndian.Uint32(t[4:8])) * math.Pow(2, -32)
return s + f
}
func parseNtpTimestampFormatSplit(t []byte) (int, int) {
seconds := int(binary.BigEndian.Uint32(t[0:4]))
fractionNano := int(float64(binary.BigEndian.Uint32(t[4:8])) * math.Pow(2, -32) * 1000000000)
return seconds, fractionNano
}
func convertNtpTimestampToIso8601ExtendedFormat(s int, f int) string {
s -= UNIX_TIME_OFFSET
t := time.Unix(int64(s), int64(f))
return t.Format(time.RFC3339Nano)
}
func parseNtpBytes(ntpQuery []byte, ipv4Disp bool, msDisp bool) ([]string, error) {
// NTP Query is 48 Bytes
// Leap Indicator、Version Number、Modeを1byte目から取る
firstByte := ntpQuery[0]
leapIndicatorByte := int(firstByte >> 6)
versionNumber := int(firstByte >> 3)
modeByte := int(firstByte & 0x07)
var leapIndicator string
if leapIndicatorByte == 0 {
leapIndicator = desc(leapIndicatorByte, "No Warning")
} else if leapIndicatorByte == 1 {
leapIndicator = desc(leapIndicatorByte, "Last minute of the day has 61 seconds")
} else if leapIndicatorByte == 2 {
leapIndicator = desc(leapIndicatorByte, "Last minute of the day has 59 seconds")
} else {
leapIndicator = desc(leapIndicatorByte, "Unknown")
}
var mode string
if modeByte == 0 {
mode = desc(modeByte, "Reserved")
} else if modeByte == 1 {
mode = desc(modeByte, "Symmetric Active")
} else if modeByte == 2 {
mode = desc(modeByte, "Symmetric Passive")
} else if modeByte == 3 {
mode = desc(modeByte, "Client")
} else if modeByte == 4 {
mode = desc(modeByte, "Server")
} else if modeByte == 5 {
mode = desc(modeByte, "Broadcast")
} else if modeByte == 6 {
mode = desc(modeByte, "NTP Control Message")
} else if modeByte == 7 {
mode = desc(modeByte, "Reserved for private use")
} else {
mode = desc(modeByte, "Unknown")
}
// Stratum
stratumByte := int(ntpQuery[1])
var stratum string
if stratumByte == 0 {
stratum = desc(stratumByte, "Unspecified or invalid")
} else if stratumByte == 1 {
stratum = desc(stratumByte, "Primary Server")
} else if stratumByte >= 2 && stratumByte <= 15 {
stratum = desc(stratumByte, "Secondary Server")
} else if stratumByte == 16 {
stratum = desc(stratumByte, "Unsynchronized")
} else {
stratum = desc(stratumByte, "Reserved")
}
// Poll
pollIntervalByte := int(ntpQuery[2])
pollInterval := strconv.Itoa(int(math.Pow(2, float64(pollIntervalByte)))) + " seconds"
fmt.Printf("Poll interval: %s\n", pollInterval)
var timeUnit string
if msDisp {
timeUnit = " ms"
} else {
timeUnit = " seconds"
}
precisionByte := int(int8(ntpQuery[3]))
precisionSeconds := math.Pow(2, float64(precisionByte))
if msDisp {
precisionSeconds *= 1000
}
precision := strconv.FormatFloat((precisionSeconds), 'f', -1, 64) + timeUnit
fmt.Printf("Precision: %s\n", precision)
// Root Delay
rootDelayBytes := ntpQuery[4:8]
rootDelaySeconds := parseNtpShortFormat(rootDelayBytes)
if msDisp {
rootDelaySeconds *= 1000
}
rootDelay := strconv.FormatFloat(rootDelaySeconds, 'f', -1, 64) + timeUnit
fmt.Printf("Root delay: %s\n", rootDelay)
// Root Dispersion
rootDispersionBytes := ntpQuery[8:12]
rootDispersionSeconds := parseNtpShortFormat(rootDispersionBytes)
if msDisp {
rootDispersionSeconds *= 1000
}
rootDispersion := strconv.FormatFloat(rootDispersionSeconds, 'f', -1, 64) + timeUnit
fmt.Printf("Root dispersion: %s\n", rootDispersion)
// Reference ID
referenceIDByte := ntpQuery[12:16]
var referenceID string
if stratumByte == 1 {
for _, b := range referenceIDByte {
if int(b) != 0 {
referenceID += string(b)
}
}
} else {
for _, b := range referenceIDByte {
referenceID += fmt.Sprintf("%02X", b)
}
// TODO: IPアドレス変換
var referenceIDArrString []string
for _, b := range referenceIDByte {
referenceIDArrString = append(referenceIDArrString, strconv.Itoa(int(b)))
}
IPFormReferenceID := strings.Join(referenceIDArrString, ".")
if ipv4Disp {
referenceID += " (IPv4 form: " + IPFormReferenceID + ")"
}
}
fmt.Printf("Reference ID: %s\n", referenceID)
// Reference Timestamp
referenceTimestampByte := ntpQuery[16:24]
referenceTimestampSecond, referenceTimestampFraction := parseNtpTimestampFormatSplit(referenceTimestampByte)
referenceTimestamp := strconv.FormatFloat(parseNtpTimestampFormat(referenceTimestampByte), 'f', -1, 64) + " (" +
convertNtpTimestampToIso8601ExtendedFormat(referenceTimestampSecond, referenceTimestampFraction) + ")"
// Origin Timestamp
originTimestampByte := ntpQuery[24:32]
originTimestampSecond, originTimestampFraction := parseNtpTimestampFormatSplit(originTimestampByte)
originTimestamp := strconv.FormatFloat(parseNtpTimestampFormat(originTimestampByte), 'f', -1, 64) + " (" +
convertNtpTimestampToIso8601ExtendedFormat(originTimestampSecond, originTimestampFraction) + ")"
// Receive Timestamp
receiveTimestampByte := ntpQuery[32:40]
receiveTimestampSecond, receiveTimestampFraction := parseNtpTimestampFormatSplit(receiveTimestampByte)
recieveTimestamp := strconv.FormatFloat(parseNtpTimestampFormat(receiveTimestampByte), 'f', -1, 64) + " (" +
convertNtpTimestampToIso8601ExtendedFormat(receiveTimestampSecond, receiveTimestampFraction) + ")"
// Transmit Timestamp
transmitTimestampByte := ntpQuery[40:48]
transmitTimestampSecond, transmitTimestampFraction := parseNtpTimestampFormatSplit(transmitTimestampByte)
transmitTimestamp := strconv.FormatFloat(parseNtpTimestampFormat(transmitTimestampByte), 'f', -1, 64) + " (" +
convertNtpTimestampToIso8601ExtendedFormat(transmitTimestampSecond, transmitTimestampFraction) + ")"
return []string{
leapIndicator,
strconv.Itoa(versionNumber),
mode,
stratum,
pollInterval,
precision,
rootDelay,
rootDispersion,
referenceID,
referenceTimestamp,
originTimestamp,
recieveTimestamp,
transmitTimestamp,
}, nil
}
func main() {
mw := &MyMainWindow{}
icon, err := walk.Resources.Icon("2")
if err != nil {
log.Fatal(err)
}
mainWindowObject := MainWindow{
AssignTo: &mw.MainWindow,
Title: WINDOW_TITLE,
Icon: icon,
Size: Size{Width: 400, Height: 480},
MinSize: Size{Width: 300, Height: 200},
Layout: VBox{},
Children: []Widget{
TextLabel{
Text: "Input NTP server host (e.g. ntp.nict.jp, time.cloudflare.com, time.google.com, time.windows.com, etc...)",
},
TextLabel{
Text: "Do not execute many times in a short time!",
},
Composite{
Layout: Grid{Columns: 3},
Children: []Widget{
Label{
Text: "NTP server host:",
},
LineEdit{
AssignTo: &mw.hostUrl,
ColumnSpan: 2,
},
Label{
Text: "Port number (Optional):",
},
NumberEdit{
AssignTo: &mw.portNumber,
Value: float64(NTP_PORT),
},
HSpacer{},
Label{
Text: "Timeout seconds (Optional):",
},
NumberEdit{
AssignTo: &mw.timeout,
Value: float64(NTP_TIMEOUT),
},
HSpacer{},
CheckBox{
AssignTo: &mw.ipv4Display,
Text: "Display IPv4 form of reference ID (e.g. 1942E605 -> 25.66.230.5)",
ToolTipText: "Note that reference ID is NOT always an IPv4 address! More details: See RFC 5905 7.3.",
ColumnSpan: 3,
},
CheckBox{
AssignTo: &mw.msDisplay,
Text: "Display time in milliseconds",
ToolTipText: "Precision, Root delay, and Root dispersion are displayed in milliseconds. They do not apply to the Poll interval.",
ColumnSpan: 3,
},
PushButton{
Text: "Execute",
OnClicked: func() {
host := strings.TrimSpace(mw.hostUrl.Text())
port := int(mw.portNumber.Value())
timeout := int(mw.timeout.Value())
if host == "" {
walk.MsgBox(mw, "Error", "NTP server host is empty!", walk.MsgBoxIconError)
return
}
if port < 0 || port > 65535 {
port = NTP_PORT
}
if timeout < 0 {
timeout = NTP_TIMEOUT
}
ntpQuery, err := reqNtp(host, port, timeout)
if err != nil {
walk.MsgBox(mw, "Error", "An error occurred during the request:\n"+err.Error(), walk.MsgBoxIconError)
return
}
parsedNtpQuery, err := parseNtpBytes(ntpQuery, mw.ipv4Display.Checked(), mw.msDisplay.Checked())
if err != nil {
walk.MsgBox(mw, "Error", "An error occurred during the parsing:\n"+err.Error(), walk.MsgBoxIconError)
return
}
mw.leapIndicator.SetText(parsedNtpQuery[0])
mw.versionNumber.SetText(parsedNtpQuery[1])
mw.mode.SetText(parsedNtpQuery[2])
mw.stratum.SetText(parsedNtpQuery[3])
mw.pollInterval.SetText(parsedNtpQuery[4])
mw.precision.SetText(parsedNtpQuery[5])
mw.rootDelay.SetText(parsedNtpQuery[6])
mw.rootDispersion.SetText(parsedNtpQuery[7])
mw.referenceID.SetText(parsedNtpQuery[8])
mw.referenceTimestamp.SetText(parsedNtpQuery[9])
mw.originTimestamp.SetText(parsedNtpQuery[10])
mw.receiveTimestamp.SetText(parsedNtpQuery[11])
mw.transmitTimestamp.SetText(parsedNtpQuery[12])
},
},
HSpacer{
ColumnSpan: 2,
},
},
},
Composite{
Layout: Grid{Columns: 2},
Children: []Widget{
Label{
Text: "Leap Indicator:",
},
LineEdit{
AssignTo: &mw.leapIndicator,
ReadOnly: true,
},
Label{
Text: "Version Number:",
},
LineEdit{
AssignTo: &mw.versionNumber,
ReadOnly: true,
},
Label{
Text: "Mode:",
},
LineEdit{
AssignTo: &mw.mode,
ReadOnly: true,
},
Label{
Text: "Stratum:",
},
LineEdit{
AssignTo: &mw.stratum,
ReadOnly: true,
},
Label{
Text: "Poll Interval:",
},
LineEdit{
AssignTo: &mw.pollInterval,
ReadOnly: true,
},
Label{
Text: "Precision:",
},
LineEdit{
AssignTo: &mw.precision,
ReadOnly: true,
},
Label{
Text: "Root Delay:",
},
LineEdit{
AssignTo: &mw.rootDelay,
ReadOnly: true,
},
Label{
Text: "Root Dispersion:",
},
LineEdit{
AssignTo: &mw.rootDispersion,
ReadOnly: true,
},
Label{
Text: "Reference ID:",
},
LineEdit{
AssignTo: &mw.referenceID,
ReadOnly: true,
},
Label{
Text: "Reference Timestamp:",
},
LineEdit{
AssignTo: &mw.referenceTimestamp,
ReadOnly: true,
},
Label{
Text: "Origin Timestamp:",
},
LineEdit{
AssignTo: &mw.originTimestamp,
ReadOnly: true,
ToolTipText: "This value is normally 0 when you are using this tool.",
},
Label{
Text: "Receive Timestamp:",
},
LineEdit{
AssignTo: &mw.receiveTimestamp,
ReadOnly: true,
},
Label{
Text: "Transmit Timestamp:",
},
LineEdit{
AssignTo: &mw.transmitTimestamp,
ReadOnly: true,
},
},
},
},
}
if _, err := mainWindowObject.Run(); err != nil {
log.Fatal(err)
os.Exit(1)
}
}