-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproto.go
More file actions
87 lines (71 loc) · 1.62 KB
/
proto.go
File metadata and controls
87 lines (71 loc) · 1.62 KB
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
package ohrad
import (
"bytes"
"encoding/binary"
"fmt"
"net"
"syscall"
)
const (
NtpMsgSize int = 48 // no auth
Jan1970 = 2208988800
NanosPerSecond = 1000 * 1000 * 1000
)
type NtpLong struct {
IntParl uint32
Fractionl uint32
}
type NtpShort struct {
IntParts uint16
Fractions uint16
}
type NtpMsg struct {
Status uint8
Stratum uint8
Ppoll uint8
Precision int8
Rootdelay NtpShort
Dispersion NtpShort
Refid uint32
Reftime NtpLong
Orgtime NtpLong
Rectime NtpLong
Xmttime NtpLong
}
func (m *NtpMsg) Bytes() []byte {
var buf bytes.Buffer
binary.Write(&buf, binary.BigEndian, m)
return buf.Bytes()
}
func NewMsg(buf []byte) *NtpMsg {
var query NtpMsg
binary.Read(bytes.NewReader(buf), binary.BigEndian, &query)
return &query
}
func GetNtpMsg(conn *net.UDPConn) (*NtpMsg, *net.UDPAddr, error) {
// FIXME: only handling no-auth messages for now
buf := make([]byte, NtpMsgSize)
n, addr, err := conn.ReadFromUDP(buf)
rectime := getTimeNow()
if n != NtpMsgSize {
Log.Debug("Invalid msg size)")
}
query := NewMsg(buf[0:n])
query.Rectime = rectime
return query, addr, err
}
func SendNtpMsg(conn *net.UDPConn, clientAddr *net.UDPAddr, msg *NtpMsg) {
msgBytes := msg.Bytes()
n, nerr := conn.WriteToUDP(msgBytes, clientAddr)
if errno, ok := nerr.(syscall.Errno); ok {
if (errno == syscall.ENOBUFS) || (errno == syscall.EHOSTUNREACH) || (errno == syscall.ENETDOWN) || (errno == syscall.EHOSTDOWN) {
return
}
Log.Debug(fmt.Sprintf("WriteToUDP: %s", errno))
return
}
if n != len(msgBytes) {
Log.Notice("Sent msg has a different size")
}
return
}