This repository has been archived by the owner on May 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathworker.go
91 lines (81 loc) · 1.76 KB
/
worker.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
package gontpd
import (
"encoding/binary"
"log"
"net"
"time"
"github.com/prometheus/client_golang/prometheus"
)
type Worker struct {
conn *net.UDPConn
cfg *Config
counter *counter
metaHdr uint64
rootRefHdr uint64
refTimeHdr uint64
}
type counter struct {
total prometheus.Counter
drop *prometheus.CounterVec
}
func (w *Worker) run(i int) {
log.Printf("worker:%d online", i)
var (
buf []byte
n int
remote *net.UDPAddr
err error
rcvTime time.Time
txTime uint64
)
buf = make([]byte, 48, 48)
// BCE
_ = buf[47]
for {
n, remote, err = w.conn.ReadFromUDP(buf)
rcvTime = time.Now()
if err != nil || remote.Port == 0 {
continue
}
if n < 48 {
if w.counter != nil {
w.counter.drop.WithLabelValues("small").Inc()
}
continue
}
if !isValidNTPRequest(buf) {
if w.counter != nil {
w.counter.drop.WithLabelValues("invalid").Inc()
}
continue
}
if w.cfg.InACL(remote.IP) {
if w.counter != nil {
w.counter.drop.WithLabelValues("acl").Inc()
}
continue
}
txTime = binary.BigEndian.Uint64(buf[transmitTimeStamp:])
binary.BigEndian.PutUint64(buf[metaOffset:], w.metaHdr)
binary.BigEndian.PutUint64(buf[rootRefOffset:], w.rootRefHdr)
binary.BigEndian.PutUint64(buf[referenceTimeStamp:], w.refTimeHdr)
binary.BigEndian.PutUint64(buf[originTimeStamp:], txTime)
binary.BigEndian.PutUint64(buf[receiveTimeStamp:], toNTPTime(rcvTime))
binary.BigEndian.PutUint64(buf[transmitTimeStamp:], toNTPTime(time.Now()))
_, err = w.conn.WriteToUDP(buf, remote)
if err != nil {
log.Println(err)
}
if w.counter != nil {
w.counter.total.Inc()
}
}
}
func isValidNTPRequest(p []byte) (r bool) {
switch p[0] &^ 0xf8 {
case 3: // modeClient
default:
return
}
return true
}