-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
371 lines (298 loc) · 7.63 KB
/
conn.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
package websocket
import (
"bufio"
"encoding/binary"
"io"
"io/ioutil"
"net"
"unicode/utf8"
)
// Close codes defined in RFC 6455.
const (
CloseNormalClosure = 1000
CloseGoingAway = 1001
CloseProtocolError = 1002
CloseUnsupportedData = 1003
CloseNoStatusReceived = 1005
CloseAbnormalClosure = 1006
CloseInvalidFramePayloadData = 1007
ClosePolicyViolation = 1008
CloseMessageTooBig = 1009
CloseMandatoryExtension = 1010
CloseInternalServerErr = 1011
CloseServiceRestart = 1012
CloseTryAgainLater = 1013
CloseTLSHandshake = 1015
)
var validReceivedCloseCodes = map[int]bool{
CloseNormalClosure: true,
CloseGoingAway: true,
CloseProtocolError: true,
CloseUnsupportedData: true,
CloseNoStatusReceived: false,
CloseAbnormalClosure: false,
CloseInvalidFramePayloadData: true,
ClosePolicyViolation: true,
CloseMessageTooBig: true,
CloseMandatoryExtension: true,
CloseInternalServerErr: true,
CloseServiceRestart: true,
CloseTryAgainLater: true,
CloseTLSHandshake: false,
}
func isValidReceivedCloseCode(code int) bool {
return validReceivedCloseCodes[code] || (code >= 3000 && code <= 4999)
}
// Conn is a type which represents the WebSocket connection.
type Conn struct {
conn net.Conn
rw *bufio.ReadWriter
reader io.Reader
writer io.WriteCloser
closeErr *CloseError
isServer bool
}
// NextReader returns the message type of the first fragmented frame
// (either TextOpcode or BinaryOpcode) and reader, using which you can receive
// other frame bytes.
//
// It discards the previous reader if it's not empty. There can be at most one
// open reader on a connection.
func (c *Conn) NextReader() (frameType byte, r io.Reader, err error) {
if c.reader != nil {
_, err = ioutil.ReadAll(c.reader)
if err != nil {
return noFrame, nil, err
}
c.reader = nil
}
for c.closeErr == nil {
fr, err := c.receive()
if err != nil {
return noFrame, nil, err
}
if fr.isText() || fr.isBinary() {
c.reader = newMessageReader(c, fr.opcode, fr.payload, !fr.isFragment)
return fr.opcode, c.reader, nil
}
}
return noFrame, nil, c.closeErr
}
// ReadMessage is a helper method for getting all fragmented frames in one message.
// It uses NextReader under the hood.
func (c *Conn) ReadMessage() (messageType byte, payload []byte, err error) {
frameType, r, err := c.NextReader()
if err != nil {
return noFrame, nil, err
}
payload, err = ioutil.ReadAll(r)
if err != nil {
return noFrame, nil, err
}
return frameType, payload, nil
}
func (c *Conn) receive() (frame, error) {
fr := frame{}
head, err := c.read(2)
if err != nil {
return fr, err
}
fr.isFragment = (head[0] & 0x80) == 0x00
fr.reserved = head[0] & 0x70
fr.opcode = head[0] & 0x0F
fr.isMasked = (head[1] & 0x80) == 0x80
length := uint64(head[1] & 0x7F)
switch length {
case 126:
lenBytes, err := c.read(2)
if err != nil {
return fr, err
}
length = uint64(binary.BigEndian.Uint16(lenBytes))
case 127:
lenBytes, err := c.read(8)
if err != nil {
return fr, err
}
length = binary.BigEndian.Uint64(lenBytes)
}
fr.length = length
var maskKey []byte
if fr.isMasked {
maskKey, err = c.read(4)
if err != nil {
return fr, err
}
}
payload, err := c.read(length)
if err != nil {
return fr, err
}
if fr.isMasked {
for i := uint64(0); i < uint64(len(payload)); i++ {
payload[i] ^= maskKey[i%4]
}
}
fr.payload = payload
if closeErr := c.validate(fr); closeErr != nil {
c.closeErr = closeErr
return fr, closeErr
}
return fr, c.processReceivedFrame(fr)
}
func (c *Conn) processReceivedFrame(fr frame) error {
switch fr.opcode {
case CloseOpcode:
closeCode := CloseNormalClosure
if len(fr.payload) >= 2 {
closeCode = int(binary.BigEndian.Uint16(fr.payload[:2]))
}
if err := c.close(closeCode); err != nil {
return err
}
c.closeErr = &CloseError{code: closeCode}
return c.closeErr
case PingOpcode:
pongFr := fr
pongFr.opcode = PongOpcode
if err := c.send(pongFr); err != nil {
return err
}
case ContinuationOpcode:
if c.reader == nil {
return c.setCloseError(errEmptyContinueFrames)
}
case TextOpcode, BinaryOpcode:
if c.reader != nil {
return c.setCloseError(errInvalidContinuationFrame)
}
}
return nil
}
func (c *Conn) read(size uint64) ([]byte, error) {
buff := make([]byte, size)
if _, err := io.ReadFull(c.rw, buff); err != nil {
return nil, err
}
return buff, nil
}
func (c *Conn) validate(fr frame) *CloseError {
if fr.isControl() && (fr.length > 125 || fr.isFragment) {
return errInvalidControlFrame
}
if fr.reserved > 0 {
return errNonZeroRSVFrame
}
if fr.opcode > BinaryOpcode && fr.opcode < CloseOpcode || fr.opcode > PongOpcode {
return errReservedOpcodeFrame
}
if fr.isClose() && len(fr.payload) != 0 {
if len(fr.payload) < 2 {
return errInvalidClosurePayload
}
code := int(binary.BigEndian.Uint16(fr.payload[:2]))
reason := fr.payload[2:]
if !isValidReceivedCloseCode(code) {
return errInvalidClosureCode
}
if !utf8.Valid(reason) {
return errInvalidUtf8Payload
}
}
return nil
}
// NextWriter returns a writer using which you can send message partially.
// The writer's Close method flushes the complete message to the network.
//
// It discards the previous writer if it's not empty. There can be at most one
// open writer on a connection.
func (c *Conn) NextWriter(messageType byte) (io.WriteCloser, error) {
if c.closeErr != nil {
return nil, c.closeErr
}
if c.writer != nil {
err := c.writer.Close()
if err != nil {
return nil, err
}
c.writer = nil
}
c.writer = newMessageWriter(c, messageType)
return c.writer, nil
}
// WriteMessage is a helper method to send message entire.
// It uses a NextWriter under the hood.
func (c *Conn) WriteMessage(messageType byte, payload []byte) error {
w, err := c.NextWriter(messageType)
if err != nil {
return err
}
_, err = w.Write(payload)
if err != nil {
return err
}
return w.Close()
}
func (c *Conn) send(fr frame) error {
data := make([]byte, 2)
data[0] = fr.opcode
if !fr.isFragment {
data[0] |= 0x80
}
length := uint64(len(fr.payload))
switch {
case length <= 125:
data[1] = byte(length)
case length <= 65535:
data[1] = 126
lenBytes := make([]byte, 2)
binary.BigEndian.PutUint16(lenBytes, uint16(length))
data = append(data, lenBytes...)
default:
data[1] = 127
lenBytes := make([]byte, 8)
binary.BigEndian.PutUint64(lenBytes, length)
data = append(data, lenBytes...)
}
if !c.isServer {
data[1] |= 0x80
maskKey := newMaskKey()
for i := 0; i < len(fr.payload); i++ {
fr.payload[i] ^= maskKey[i%len(maskKey)]
}
data = append(data, maskKey[:]...)
}
data = append(data, fr.payload...)
return c.write(data)
}
func (c *Conn) write(data []byte) error {
if _, err := c.rw.Write(data); err != nil {
return err
}
return c.rw.Flush()
}
func (c *Conn) setCloseError(err *CloseError) error {
c.closeErr = err
return err
}
// Close sends control normal close frame if wasn't any errors. After that
// the tcp connection will be closed. Otherwise, it sends close frame
// with status code depending on happened error.
func (c *Conn) Close() error {
if c.closeErr != nil {
return c.close(c.closeErr.code)
}
return c.close(CloseNormalClosure)
}
func (c *Conn) close(statusCode int) error {
payload := make([]byte, 2)
binary.BigEndian.PutUint16(payload, uint16(statusCode))
fr := frame{
opcode: CloseOpcode,
payload: payload,
}
if err := c.send(fr); err != nil {
return err
}
return c.conn.Close()
}