-
Notifications
You must be signed in to change notification settings - Fork 2
/
webntp.go
316 lines (284 loc) · 6.08 KB
/
webntp.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
package webntp
import (
"bufio"
"io"
"math"
"sort"
"strconv"
"time"
"unicode"
)
// Timestamp is posix unix timestamp.
type Timestamp time.Time
var zeroEpochTime Timestamp
func init() {
t, err := time.Parse(time.RFC3339Nano, "1970-01-01T00:00:00Z")
if err != nil {
panic(err)
}
zeroEpochTime = Timestamp(t)
}
// MarshalJSON converts the timestamp to JSON number.
// The number is unix timestamp.
func (t Timestamp) MarshalJSON() ([]byte, error) {
// write seconds.
tt := time.Time(t)
b := make([]byte, 0, 20)
b = strconv.AppendInt(b, tt.Unix(), 10)
b = append(b, '.')
// write microsecond
m := (time.Duration(tt.Nanosecond()) + 500*time.Nanosecond) / time.Microsecond
switch {
case m < 10:
b = append(b, '0', '0', '0', '0', '0')
case m < 100:
b = append(b, '0', '0', '0', '0')
case m < 1000:
b = append(b, '0', '0', '0')
case m < 10000:
b = append(b, '0', '0')
case m < 100000:
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(m), 10)
return b, nil
}
// UnmarshalJSON converts JSON number to a timestamp.
// The number is unix timestamp.
func (t *Timestamp) UnmarshalJSON(b []byte) error {
intSec, nanoSec := int64(0), int64(0)
nanoSecPos := int64(1e9)
seenDot := false
seenNumber := false
seenSign := false
sign := int64(1)
for _, c := range b {
switch c {
case '.':
seenDot = true
case '-':
if seenDot || seenNumber || seenSign {
goto FALLBACK
}
sign = -1
seenSign = true
case '+':
if seenDot || seenNumber || seenSign {
goto FALLBACK
}
seenSign = true
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
seenNumber = true
if seenDot {
nanoSecPos /= 10
nanoSec += nanoSecPos * int64(c-'0')
} else {
intSec = intSec*10 + int64(c-'0')
}
default:
goto FALLBACK
}
}
*t = Timestamp(time.Unix(sign*intSec, nanoSec))
return nil
FALLBACK:
timestamp, err := strconv.ParseFloat(string(b), 64)
if err != nil {
return err
}
fintSec, fracSec := math.Modf(timestamp)
*t = Timestamp(time.Unix(int64(fintSec), int64(fracSec*1e9)))
return nil
}
// Subprotocol is a subprotocol name for websocket.
const Subprotocol = "webntp.shogo82148.com"
// Response is a response from webntp server.
type Response struct {
// ID is the id of the web-ntp server.
ID string `json:"id"`
// InitiateTime is the time that the request has been sent.
InitiateTime Timestamp `json:"it"`
// SendTime is the time that the response has been sent.
SendTime Timestamp `json:"st"`
// Time is a same as SendTime.
// It is for htptime compatibility.
Time Timestamp `json:"time"`
// Leap is from TAI to UTC. (**before** Response.Next)
Leap int `json:"leap"`
// Next is the time of next or last leap second event.
Next Timestamp `json:"next"`
// Step describes next or last leap second is insertion or deletion.
// +1 is insertion, -1 is deletion.
Step int `json:"step"`
}
// LeapSecond is information for leap-seconds
type LeapSecond struct {
// At is the time to insert/delete a leap second.
At time.Time
// Leap is offset from TAI to UTC. (**after** LeapSecond.Time)
Leap int
// Step describes next leap second is insertion or deletion.
// +1 is insertion, -1 is deletion.
Step int
}
// LeapSecondsList is the contents of leap-second.list.
type LeapSecondsList struct {
LeapSeconds []LeapSecond
UpdateAt time.Time
ExpireAt time.Time
}
type leapSecondsParser struct {
r *bufio.Reader
list []LeapSecond
updateAt time.Time
expireAt time.Time
err error
}
const ntpEpochOffset = (70*365 + 17) * 86400
// ParseLeapSecondsList parses leap-second.list.
func ParseLeapSecondsList(r io.Reader) (*LeapSecondsList, error) {
p := &leapSecondsParser{
r: bufio.NewReaderSize(r, 1024),
}
var err error
LOOP:
for {
var r rune
r, _, err = p.r.ReadRune()
if err != nil {
break
}
switch {
case unicode.IsSpace(r):
continue
case r == '#':
// comment line
p.parseComment()
case '0' <= r && r <= '9':
// leap second line
err := p.r.UnreadRune()
if err != nil {
p.err = err
break LOOP
}
p.parseLeapSecond()
default:
// unknown line
p.skipLine()
}
if p.err != nil {
return nil, p.err
}
}
sort.Slice(p.list, func(i, j int) bool {
return p.list[i].At.Before(p.list[j].At)
})
lastLeap := p.list[0].Leap
for i := 1; i < len(p.list); i++ {
p.list[i].Step = p.list[i].Leap - lastLeap
lastLeap, p.list[i].Leap = p.list[i].Leap, lastLeap
}
return &LeapSecondsList{
LeapSeconds: p.list[1:],
UpdateAt: p.updateAt,
ExpireAt: p.expireAt,
}, nil
}
func (p *leapSecondsParser) parseComment() {
var r rune
r, _, p.err = p.r.ReadRune()
if p.err != nil {
return
}
switch r {
case '\n':
return
case ' ':
// normal comment line
case '$':
// last update date
i := p.getInt(64)
p.updateAt = time.Unix(i-ntpEpochOffset, 0)
case '@':
// the expiration date
i := p.getInt(64)
p.expireAt = time.Unix(i-ntpEpochOffset, 0)
case 'h':
// hash value of the data
default:
// unknown comment line. ignore it.
}
p.skipLine()
}
func (p *leapSecondsParser) parseLeapSecond() {
at := p.getInt(64)
p.skipSpace()
leap := p.getInt(0)
p.skipSpace()
p.skipLine()
if p.err != nil {
return
}
p.list = append(p.list, LeapSecond{
At: time.Unix(at-ntpEpochOffset, 0),
Leap: int(leap),
})
}
func (p *leapSecondsParser) skipSpace() {
if p.err != nil {
return
}
for {
r, _, err := p.r.ReadRune()
if err != nil {
p.err = err
return
}
if !unicode.IsSpace(r) {
p.err = p.r.UnreadRune()
return
}
}
}
func (p *leapSecondsParser) skipLine() {
if p.err != nil {
return
}
for {
r, _, err := p.r.ReadRune()
if err != nil {
p.err = err
return
}
if r == '\n' {
break
}
}
}
func (p *leapSecondsParser) getInt(size int) int64 {
p.skipSpace()
if p.err != nil {
return 0
}
buf := make([]byte, 0, 20)
var err error
var r rune
for {
r, _, err = p.r.ReadRune()
if err != nil {
break
}
if r < '0' || r > '9' {
err = p.r.UnreadRune()
break
}
buf = append(buf, byte(r))
}
if len(buf) == 0 && err != nil {
p.err = err
return 0
}
i, err := strconv.ParseInt(string(buf), 10, size)
p.err = err
return i
}