-
Notifications
You must be signed in to change notification settings - Fork 1
/
websocket.go
569 lines (496 loc) · 14.3 KB
/
websocket.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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
// Package websocket implements “The WebSocket Protocol” RFC 6455, version 13.
package websocket
import (
"errors"
"fmt"
"io"
"net"
"sync/atomic"
"time"
"unicode/utf8"
)
// Opcode defines the interpretation of a frame payload.
const (
// Continuation for streaming data.
Continuation = iota
// Text for UTF-8 encoded data.
Text
// Binary for opaque data.
Binary
// Reserved3 is reserved for further non-control frames.
Reserved3
// Reserved4 is reserved for further non-control frames.
Reserved4
// Reserved5 is reserved for further non-control frames.
Reserved5
// Reserved6 is reserved for further non-control frames.
Reserved6
// Reserved7 is reserved for further non-control frames.
Reserved7
// Close for disconnect notification.
Close
// Ping to request Pong.
Ping
// Pong may be send unsolicited too.
Pong
// Reserved11 is reserved for further control frames.
Reserved11
// Reserved12 is reserved for further control frames.
Reserved12
// Reserved13 is reserved for further control frames.
Reserved13
// Reserved14 is reserved for further control frames.
Reserved14
// Reserved15 is reserved for further control frames.
Reserved15
)
// Defined Status Codes
const (
// NormalClose means that the purpose for which the connection was
// established has been fulfilled.
NormalClose = 1000
// GoingAway is a leave like a server going down or a browser moving on.
GoingAway = 1001
// ProtocolError rejects standard violation.
ProtocolError = 1002
// CannotAccept rejects a data type receival.
CannotAccept = 1003
// NoStatusCode is allowed by the protocol.
NoStatusCode = 1005
// AbnormalClose signals a disconnect without Close.
AbnormalClose = 1006
// Malformed rejects data that is not consistent with it's type, like an
// illegal UTF-8 sequence for Text.
Malformed = 1007
// Policy rejects a message due to a violation.
Policy = 1008
// TooBig rejects a message due to size constraints.
TooBig = 1009
// WantExtension signals the client's demand for the server to negotiate
// one or more extensions.
WantExtension = 1010
// Unexpected condition prevented the server from fulfilling the request.
Unexpected = 1011
)
var errUTF8 = errors.New("websocket: invalid UTF-8 sequence in text payload")
// ClosedError is a status code. Atomic Close support prevents Go issue 4373.
// Even after receiving a ClosedError, Conn.Close must still be called.
type ClosedError uint
// Error honors the error interface.
func (e ClosedError) Error() string {
switch e {
case NoStatusCode:
return "websocket: connection closed"
case AbnormalClose:
return "websocket: connection closed abnormally"
default:
return fmt.Sprintf("websocket: connection closed, status code %04d", e)
}
}
// Timeout honors the net.Error interface.
func (e ClosedError) Timeout() bool { return false }
// Temporary honors the net.Error interface.
func (e ClosedError) Temporary() bool { return false }
// SendClose is a high-level abstraction for safety and convenience. The client
// is notified on best effort basis, including the optional free-form reason.
// Use 123 bytes of UTF-8 or less for submission.
//
// When the connectection already received or send a Close then only the first
// status code remains in effect. Redundant status codes are discarded.
// The return always is a CloseError with the first status code.
//
// Multiple goroutines may invoke SendClose simultaneously. SendClose may be
// invoked simultaneously with any other method from Conn.
func (c *Conn) SendClose(statusCode uint, reason string) error {
if !atomic.CompareAndSwapUint32(&c.statusCode, 0, uint32(statusCode|statusCodeSetFlag)) {
// already closed
return c.closeError()
}
// “range 0-999 are not used” and the others “MUST NOT be set”
send := statusCode > 999 && statusCode != NoStatusCode && statusCode != AbnormalClose && statusCode != 1015
// control frame payload limit is 125 bytes; status code takes 2
if send && (len(reason) > 123 || !utf8.ValidString(reason)) {
send = false
}
c.writeMutex.Lock()
// best effort close notification; no pending errors
if c.writeBufN == 0 && c.writePayloadN == 0 {
c.writeBuf[0] = Close | finalFlag
if !send {
c.writeBuf[1] = 0
c.Conn.Write(c.writeBuf[:2])
} else {
c.writeBuf[1] = byte(len(reason) + 2)
byteOrder.PutUint16(c.writeBuf[2:4], uint16(statusCode))
copy(c.writeBuf[4:], reason)
c.Conn.Write(c.writeBuf[:4+len(reason)])
}
}
c.writeMutex.Unlock()
return ClosedError(statusCode)
}
// Send is a high-level abstraction for safety and convenience.
// The opcode must be in range [1, 15] like Text, Binary or Ping.
// WireTimeout limits the frame transmission time. On expiry, the connection
// is closed with status code 1008 [Policy].
// All error returns are fatal to the connection.
//
// Multiple goroutines may invoke Send simultaneously. Send may be invoked
// simultaneously with any other high-level method from Conn. Note that when
// Send interrupts SendStream, then the opcode of Send is further reduced to
// range [8, 15]. Simultaneous invokation of any of the low-level net.Conn
// methods can currupt the connection state.
func (c *Conn) Send(opcode uint, message []byte, wireTimeout time.Duration) error {
c.writeMutex.Lock()
c.SetWriteMode(opcode, true)
_, err := c.writeWithRetry(message, wireTimeout)
c.writeMutex.Unlock()
return err
}
// SendStream is an alternative to Send.
// The opcode must be in range [1, 7] like Text or Binary.
// WireTimeout limits the frame transmission time. On expiry, the connection
// is closed with status code 1008 [Policy].
// All errors from the io.WriteCloser other than io.ErrClosedPipe are fatal to
// the connection. Check Close for errors too!
//
// The stream must be closed before any other invocation to SendStream is made
// and Send may only interrupt with control frames—opcode range [8, 15].
// Multiple goroutines may invoke the io.WriteCloser methods simultaneously.
// Simultaneous invokation of either SendStream or the io.WriteCloser with any
// of the low-level net.Conn methods can currupt the connection state.
func (c *Conn) SendStream(opcode uint, wireTimeout time.Duration) io.WriteCloser {
c.SetWriteMode(opcode, false)
switch opcode {
default:
return &messageWriter{c, wireTimeout, opcode}
case Text:
return &textWriter{conn: c, wireTimeout: wireTimeout, opcode: opcode}
}
}
type messageWriter struct {
conn *Conn
wireTimeout time.Duration
opcode uint
}
func (w *messageWriter) Write(p []byte) (n int, err error) {
w.conn.writeMutex.Lock()
if w.opcode == Close {
err = io.ErrClosedPipe
} else {
w.conn.SetWriteMode(w.opcode, false)
w.opcode = Continuation
n, err = w.conn.writeWithRetry(p, w.wireTimeout)
}
w.conn.writeMutex.Unlock()
return
}
func (w messageWriter) Close() (err error) {
w.conn.writeMutex.Lock()
if w.opcode != Close {
w.conn.SetWriteMode(w.opcode, true)
w.opcode = Close
_, err = w.conn.writeWithRetry(nil, w.wireTimeout)
}
w.conn.writeMutex.Unlock()
return
}
type textWriter struct {
conn *Conn
wireTimeout time.Duration
opcode uint
remain [utf8.UTFMax]byte
remainN int
}
func (w *textWriter) Write(p []byte) (n int, err error) {
w.conn.writeMutex.Lock()
if w.opcode == Close {
w.conn.writeMutex.Unlock()
return 0, io.ErrClosedPipe
}
// complete partial UTF-8 sequence if there's any
for w.remainN != 0 {
if n >= len(p) {
return // consumed entire payload
}
// add one byte
w.remain[w.remainN] = p[n]
w.remainN++
n++
r, _ := utf8.DecodeRune(w.remain[:w.remainN])
if r != utf8.RuneError {
p = append(w.remain[:w.remainN], p...)
n -= w.remainN // makes n negative
w.remainN = 0
} else if w.remainN >= utf8.UTFMax {
return n, errUTF8
}
}
// determine last complete rune end
end := len(p)
if !utf8.Valid(p) {
for end--; end >= 0; end-- {
if p[end]&0xc0 != 0xc0 {
break // multi-byte start
}
}
if end < len(p)-utf8.UTFMax || !utf8.Valid(p[:end]) {
return n, errUTF8
}
}
w.conn.SetWriteMode(w.opcode, false)
w.opcode = Continuation
done, err := w.conn.writeWithRetry(p, w.wireTimeout)
n += done
w.remainN = copy(w.remain[:], p[end:])
w.conn.writeMutex.Unlock()
return n, err
}
func (w textWriter) Close() (err error) {
if w.remainN != 0 {
return errUTF8
}
w.conn.writeMutex.Lock()
if w.opcode != Close {
w.conn.SetWriteMode(w.opcode, true)
w.opcode = Close
_, err = w.conn.writeWithRetry(nil, w.wireTimeout)
}
w.conn.writeMutex.Unlock()
return
}
// caller must hold the writeMutex lock
func (c *Conn) writeWithRetry(p []byte, timeout time.Duration) (n int, err error) {
var retryDelay = time.Microsecond
c.SetWriteDeadline(time.Now().Add(timeout))
n, err = c.write(p)
for err != nil {
e, ok := err.(net.Error)
if ok && e.Timeout() {
c.setClose(Policy, "write timeout")
return
}
if !ok || !e.Temporary() {
return
}
time.Sleep(retryDelay)
if retryDelay < time.Second {
retryDelay *= 2
}
var more int
more, err = c.write(p[n:])
n += more
}
return
}
// Receive is a high-level abstraction (from Read) for safety and convenience.
// The opcode return is in range [1, 7]. Control frames are dealed with.
// Size defines the amount of bytes in Reader or negative when unknown.
//
// Receive must be called sequentially. Reader must be fully consumed before
// the next call to Receive. Interruptions from other calls to Receive or Read
// may cause protocol violations.
//
// WireTimeout is the limit for Read [frame receival] and idleTimeout limits
// the amount of time to wait for arrival.
func (c *Conn) Receive(buf []byte, wireTimeout, idleTimeout time.Duration) (opcode uint, n int, err error) {
n, opcode, final, err := c.readWithRetry(buf, idleTimeout)
if err != nil {
return opcode, n, err
}
if opcode == Continuation {
return opcode, n, c.SendClose(ProtocolError, "anonymous continuation")
}
for !final {
if n >= len(buf) {
c.SendClose(TooBig, "")
return opcode, n, ErrOverflow
}
more, opcode, moreFinal, err := c.readWithRetry(buf[n:], wireTimeout)
if opcode != Continuation { // also valid when err != nil
return opcode, n, c.SendClose(ProtocolError, "fragmented message interrupted")
}
n += more
if err != nil {
return opcode, n, err
}
final = moreFinal
}
if opcode == Text && !utf8.Valid(buf[:n]) {
return opcode, n, errUTF8
}
return opcode, n, nil
}
// ReceiveStream is a high-level abstraction (from Read) for safety and
// convenience. The opcode return is in range [1, 7]. Control frames are dealed
// with.
//
// Receive must be called sequentially. Reader must be fully consumed before
// the next call to Receive. Interruptions from other calls to Receive or Read
// may cause protocol violations.
//
// WireTimeout is the limit for Read [frame receival] and idleTimeout limits
// the amount of time to wait for arrival.
func (c *Conn) ReceiveStream(wireTimeout, idleTimeout time.Duration) (opcode uint, r io.Reader, err error) {
_, opcode, final, err := c.readWithRetry(nil, idleTimeout)
if err != nil {
return 0, nil, err
}
if opcode == Continuation {
return 0, nil, c.SendClose(ProtocolError, "anonymous continuation")
}
switch {
case final:
r = readEOF{}
case opcode == Text:
r = &textReader{
conn: c,
wireTimeout: wireTimeout,
}
default:
r = &messageReader{
conn: c,
wireTimeout: wireTimeout,
}
}
return opcode, r, nil
}
type messageReader struct {
conn *Conn
wireTimeout time.Duration
err error
}
func (r *messageReader) Read(p []byte) (n int, err error) {
if r.err != nil {
return 0, r.err
}
n, opcode, final, err := r.conn.readWithRetry(p, r.wireTimeout)
if opcode != Continuation { // also valid when err != nil
return 0, r.conn.SendClose(ProtocolError, "fragmented message interrupted")
}
if final {
r.err = io.EOF
if err == nil {
err = io.EOF
}
}
return n, err
}
type textReader struct {
conn *Conn
wireTimeout time.Duration
err error
tail [utf8.UTFMax - 1]byte
tailN int
}
func (r *textReader) Read(p []byte) (n int, err error) {
if r.err != nil {
return 0, r.err
}
// start with remainder
n = r.tailN
for i := range p {
if i >= n {
break
}
p[i] = r.tail[i]
}
// actual read
more, opcode, final, err := r.conn.readWithRetry(p[n:], r.wireTimeout)
if opcode != Continuation { // also valid when err != nil
return n, r.conn.SendClose(ProtocolError, "fragmented message interrupted")
}
n += more
// validation overrules I/O errors; received payload shoud be valid
if !utf8.Valid(p[:n]) {
if final {
return n, errUTF8
}
// last rune might be partial
end := n
for end--; end >= 0; end-- {
if p[end]&0xc0 != 0xc0 {
break // multi-byte start
}
}
if end+utf8.UTFMax >= n || !utf8.Valid(p[:end]) {
return n, errUTF8
}
r.tailN = copy(r.tail[:], p[end:])
n = end
}
if final {
r.err = io.EOF
if err == nil {
err = io.EOF
}
}
return n, err
}
type readEOF struct{}
func (r readEOF) Read([]byte) (int, error) {
return 0, io.EOF
}
func (c *Conn) readWithRetry(p []byte, timeout time.Duration) (n int, opcode uint, final bool, err error) {
var retryDelay = time.Microsecond
for {
c.SetReadDeadline(time.Now().Add(timeout))
n, err = c.Read(p)
for err != nil {
e, ok := err.(net.Error)
if ok && e.Timeout() {
c.SendClose(Policy, "read timeout")
return
}
if !ok || !e.Temporary() {
return
}
time.Sleep(retryDelay)
if retryDelay < time.Second {
retryDelay *= 2
}
var more int
more, err = c.Read(p)
n += more
}
opcode, final = c.ReadMode()
if opcode&ctrlFlag == 0 {
return
}
err = c.gotCtrl(opcode, n)
if err != nil {
return
}
}
}
// GotCtrl deals with the controll frame in the read buffer.
func (c *Conn) gotCtrl(opcode uint, readN int) error {
switch opcode {
case Ping:
// reuse read buffer for pong frame
c.readBuf[4] = Pong | finalFlag
c.readBuf[5] = byte(readN + c.readPayloadN)
pongFrame := c.readBuf[4 : 6+readN+c.readPayloadN]
c.writeMutex.Lock()
defer c.writeMutex.Unlock()
n, err := c.Conn.Write(pongFrame)
for err != nil {
e, ok := err.(net.Error)
if ok && e.Timeout() {
c.setClose(Policy, "write timeout")
return err
}
if !ok || !e.Temporary() {
return err
}
time.Sleep(100 * time.Microsecond)
var more int
more, err = c.Conn.Write(pongFrame[n:])
n += more
}
}
// flush payload
c.readBufDone += c.readPayloadN
c.readPayloadN = 0
return nil
}