-
Notifications
You must be signed in to change notification settings - Fork 0
/
wsoding.go
851 lines (793 loc) · 20.9 KB
/
wsoding.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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
package wsoding
import (
"context"
"crypto/rand"
"crypto/sha1"
"encoding/base64"
"errors"
"fmt"
"io"
"math"
"strings"
"syscall"
"github.com/mdlayher/socket"
)
const chunkSize int = 1024
type WS struct {
Sock *socket.Conn
Debug bool
Client bool
}
func (ws *WS) Close() error {
// Base on the ideas from https://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable
// Informing the OS that we are not planning to send anything anymore
if err := ws.Sock.Shutdown(syscall.SHUT_WR); err != nil {
return err
}
// Depleting input before closing socket, so the OS does not send RST just because we have some input pending on close
buffer := make([]byte, 1024)
for {
n, err := ws.Sock.Read(buffer)
if err != nil {
if !errors.Is(err, io.EOF) {
return err
}
}
if n == 0 {
break
}
}
// TODO: consider depleting the send buffer on Linux with ioctl(fd, SIOCOUTQ, &outstanding)
return ws.Sock.Close() // Actually destroying the socket
}
func (ws *WS) readEntireBufferRaw(buffer []byte) error {
for len(buffer) > 0 {
n, err := ws.Sock.Read(buffer)
if err != nil {
return err
}
buffer = buffer[n:]
}
return nil
}
func (ws *WS) writeEntireBufferRaw(buffer []byte) error {
for len(buffer) > 0 {
n, err := ws.Sock.Write(buffer)
if err != nil {
return err
}
buffer = buffer[n:]
}
return nil
}
func (ws *WS) peekRaw(buffer []byte) (int, error) {
n, _, err := ws.Sock.Recvfrom(context.TODO(), buffer, syscall.MSG_PEEK)
if err != nil {
return 0, err
}
return n, nil
}
// TODO: make nonblocking version of c3ws::accept
func Accept(sock *socket.Conn) (WS, error) {
ws := WS{
Sock: sock,
Client: false,
}
err := ws.ServerHandshake()
if err != nil {
return WS{}, err
}
return ws, nil
}
// TODO: connect should just accept a ws/wss URL
func Connect(sock *socket.Conn, host string, endpoint string) (WS, error) {
ws := WS{
Sock: sock,
Client: true,
}
err := ws.ClientHandshake(host, endpoint)
if err != nil {
return WS{}, err
}
return ws, nil
}
func (ws *WS) ServerHandshake() error {
// TODO: Ws.server_handshake assumes that request fits into 1024 bytes
buffer := make([]byte, 1024)
bufferSize, err := ws.peekRaw(buffer)
if err != nil {
return err
}
request := string(buffer[:bufferSize])
secWebSocketKey, err := parseSecWebSocketKeyFromRequest(&request)
if err != nil {
return err
}
_, err = ws.Sock.Read(buffer[0 : bufferSize-len(request)])
if err != nil {
return err
}
var handshake strings.Builder
handshake.Grow(1024)
handshake.WriteString("HTTP/1.1 101 Switching Protocols\r\n")
handshake.WriteString("Upgrade: websocket\r\n")
handshake.WriteString("Connection: Upgrade\r\n")
handshake.WriteString(fmt.Sprintf("Sec-WebSocket-Accept: %s\r\n", computeSecWebSocketAccept(secWebSocketKey)))
handshake.WriteString("\r\n")
_, err = ws.Sock.Write([]byte(handshake.String()))
if err != nil {
return err
}
return nil
}
// https://datatracker.ietf.org/doc/html/rfc6455#section-1.3
// TODO: Ws.client_handshake should just accept a ws/wss URL
func (ws *WS) ClientHandshake(host, endpoint string) error {
var handshake strings.Builder
handshake.Grow(1024)
// TODO: customizable resource path
handshake.WriteString(fmt.Sprintf("GET %s HTTP/1.1\r\n", endpoint))
handshake.WriteString(fmt.Sprintf("Host: %s\r\n", host))
handshake.WriteString("Upgrade: websocket\r\n")
handshake.WriteString("Connection: Upgrade\r\n")
// TODO: Custom WebSocket key
// Maybe even hardcode something that identifies c3ws?
handshake.WriteString("Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n")
handshake.WriteString("Sec-WebSocket-Version: 13\r\n")
handshake.WriteString("\r\n")
_, err := ws.Sock.Write([]byte(handshake.String()))
if err != nil {
return err
}
// TODO: Ws.client_handshake assumes that response fits into 1024 bytes
buffer := make([]byte, 1024)
bufferSize, err := ws.peekRaw(buffer)
if err != nil {
return err
}
response := string(buffer[0:bufferSize])
secWebSocketAccept, err := parseSecWebSocketAcceptFromResponse(&response)
if err != nil {
return err
}
_, err = ws.Sock.Read(buffer[0 : bufferSize-len(response)])
if err != nil {
return err
}
if secWebSocketAccept != "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=" {
return ErrClientHandshakeBadAccept
}
return nil
}
func (ws *WS) SendFrame(fin bool, opcode WSOpcode, payload []byte) error {
if ws.Debug {
fmt.Printf("WSODING DEBUG: TX FRAME: FIN(%v), OPCODE(%s), RSV(000), PAYLOAD_LEN: %d\n", fin, opcode.name(), len(payload))
}
// Send FIN and OPCODE
{
// NOTE: FIN is always set
data := byte(opcode)
if fin {
data |= (1 << 7)
}
err := ws.writeEntireBufferRaw([]byte{data})
if err != nil {
return err
}
}
// Send masked and payload length
{
// TODO: do we need to reverse the bytes on a machine with a different endianess than x86?
// NOTE: client frames are always masked
if len(payload) < 126 {
var data byte
if ws.Client {
data = 1 << 7
}
data |= byte(len(payload))
err := ws.writeEntireBufferRaw([]byte{data})
if err != nil {
return err
}
} else if len(payload) <= math.MaxUint16 {
var data byte
if ws.Client {
data = 1 << 7
}
data |= 126
err := ws.writeEntireBufferRaw([]byte{data})
if err != nil {
return err
}
length := []byte{
byte(len(payload)>>(8*1)) & 0xFF,
byte(len(payload)>>(8*0)) & 0xFF}
err = ws.writeEntireBufferRaw(length)
if err != nil {
return err
}
} else if len(payload) > math.MaxUint16 {
var data byte
if ws.Client {
data = 1 << 7
}
data |= 127
length := []byte{
byte(len(payload)>>(8*7)) & 0xFF,
byte(len(payload)>>(8*6)) & 0xFF,
byte(len(payload)>>(8*5)) & 0xFF,
byte(len(payload)>>(8*4)) & 0xFF,
byte(len(payload)>>(8*3)) & 0xFF,
byte(len(payload)>>(8*2)) & 0xFF,
byte(len(payload)>>(8*1)) & 0xFF,
byte(len(payload)>>(8*0)) & 0xFF}
err := ws.writeEntireBufferRaw([]byte{data})
if err != nil {
return err
}
err = ws.writeEntireBufferRaw(length)
if err != nil {
return err
}
}
}
if ws.Client {
// Generate and send mask
var mask [4]byte
rand.Read(mask[:])
err := ws.writeEntireBufferRaw(mask[:])
if err != nil {
return err
}
for i := 0; i < len(payload); {
chunk := make([]byte, 1024)
chunkSize := 0
for i < len(payload) && chunkSize < len(chunk) {
chunk[chunkSize] = payload[i] ^ mask[i%4]
chunkSize++
i++
}
err := ws.writeEntireBufferRaw(chunk[0:chunkSize])
if err != nil {
return err
}
}
} else {
err := ws.writeEntireBufferRaw(payload)
if err != nil {
return err
}
}
return nil
}
func (ws *WS) SendMessage(kind WSMessageKind, payload []byte) error {
first := true
for {
length := len(payload)
if length > chunkSize {
length = chunkSize
}
fin := len(payload)-length == 0
opcode := OpCodeCONT
if first {
opcode = WSOpcode(kind)
}
if opcode == OpCodeCONT && len(payload) == 0 {
break
}
err := ws.SendFrame(fin, opcode, payload[0:length])
if err != nil {
return err
}
payload = payload[length:]
first = false
if len(payload) == 0 {
break
}
}
return nil
}
func (ws *WS) SendText(text string) error {
return ws.SendMessage(MessageTEXT, []byte(text))
}
func (ws *WS) SendBinary(binary []byte) error {
return ws.SendMessage(MessageBIN, binary)
}
func (ws *WS) readFrameHeader() (WSFrameHeader, error) {
header := make([]byte, 2)
// Read the header
err := ws.readEntireBufferRaw(header)
if err != nil {
return WSFrameHeader{}, err
}
frameHeader := WSFrameHeader{
fin: itob(headerMacro(header, "fin")),
rsv1: itob(headerMacro(header, "rsv1")),
rsv2: itob(headerMacro(header, "rsv2")),
rsv3: itob(headerMacro(header, "rsv3")),
opcode: WSOpcode(headerMacro(header, "opcode")),
masked: itob(headerMacro(header, "mask")),
}
// Parse the payload length
{
// TODO: do we need to reverse the bytes on a machine with a different endianess than x86?
length := headerMacro(header, "payload_len")
switch length {
case 126:
extLen := make([]byte, 2)
err := ws.readEntireBufferRaw(extLen)
if err != nil {
return WSFrameHeader{}, err
}
for i := 0; i < len(extLen); i++ {
frameHeader.payloadLen = (frameHeader.payloadLen << 8) | int(extLen[i])
}
case 127:
extLen := make([]byte, 8)
err := ws.readEntireBufferRaw(extLen)
if err != nil {
return WSFrameHeader{}, err
}
for i := 0; i < len(extLen); i++ {
frameHeader.payloadLen = (frameHeader.payloadLen << 8) | int(extLen[i])
}
default:
frameHeader.payloadLen = int(length)
}
}
if ws.Debug {
fmt.Printf("WSODING DEBUG: RX FRAME: FIN(%v), OPCODE(%s), RSV(%d%d%d), PAYLOAD_LEN: %d\n", frameHeader.fin, frameHeader.opcode.name(), btoi(frameHeader.rsv1), btoi(frameHeader.rsv2), btoi(frameHeader.rsv3),
frameHeader.payloadLen)
}
// RFC 6455 - Section 5.5:
// > All control frames MUST have a payload length of 125 bytes or less
// > and MUST NOT be fragmented.
if frameHeader.opcode.isControl() && (frameHeader.payloadLen > 125 || !frameHeader.fin) {
return WSFrameHeader{}, ErrControlFrameTooBig
}
// RFC 6455 - Section 5.2:
// > RSV1, RSV2, RSV3: 1 bit each
// >
// > MUST be 0 unless an extension is negotiated that defines meanings
// > for non-zero values. If a nonzero value is received and none of
// > the negotiated extensions defines the meaning of such a nonzero
// > value, the receiving endpoint MUST _Fail the WebSocket
// > Connection_.
if frameHeader.rsv1 || frameHeader.rsv2 || frameHeader.rsv3 {
return WSFrameHeader{}, ErrReservedBitsNotNegotiated
}
// Read the mask if masked
if frameHeader.masked {
err := ws.readEntireBufferRaw(frameHeader.mask[:])
if err != nil {
return WSFrameHeader{}, err
}
}
return frameHeader, nil
}
func (ws *WS) readFramePayloadChunk(frameHeader WSFrameHeader, payload []byte, payloadSize int) (int, error) {
if payloadSize >= len(payload) {
return 0, nil
}
unfinishedPayload := payload[payloadSize:]
n, err := ws.Sock.Read(unfinishedPayload)
if err != nil {
return 0, err
}
if frameHeader.masked {
for i := range unfinishedPayload {
unfinishedPayload[i] ^= frameHeader.mask[(payloadSize+i)%4]
}
}
return n, nil
}
func (ws *WS) readFrameEntirePayload(frameHeader WSFrameHeader) ([]byte, error) {
payload := make([]byte, frameHeader.payloadLen)
payloadSize := 0
for payloadSize < len(payload) {
n, err := ws.readFramePayloadChunk(frameHeader, payload, payloadSize)
if err != nil {
return nil, err
}
payloadSize += n
}
return payload, nil
}
func (ws *WS) ReadMessage() (*WSMessage, error) {
var message WSMessage
payload := make([]byte, 0, 1024)
var cont bool
var verifyPos int
loop:
for {
frame, err := ws.readFrameHeader()
if err != nil {
return nil, err
}
if frame.opcode.isControl() {
switch frame.opcode {
case OpCodeCLOSE:
return nil, ErrCloseFrameSent
case OpCodePING:
b, err := ws.readFrameEntirePayload(frame)
if err != nil {
return nil, err
}
err = ws.SendFrame(true, OpCodePONG, b)
if err != nil {
return nil, err
}
case OpCodePONG:
_, err := ws.readFrameEntirePayload(frame)
if err != nil {
return nil, err
}
// Unsolicited PONGs are just ignored
break loop
default:
return nil, ErrUnexpectedOpCode
}
} else {
if !cont {
switch frame.opcode {
case OpCodeTEXT, OpCodeBIN:
message.Kind = WSMessageKind(frame.opcode)
default:
return nil, ErrUnexpectedOpCode
}
cont = true
} else {
if frame.opcode != OpCodeCONT {
return nil, ErrUnexpectedOpCode
}
}
framePayload := make([]byte, frame.payloadLen)
var framePayloadSize int
for framePayloadSize < len(framePayload) {
n, err := ws.readFramePayloadChunk(frame, framePayload, framePayloadSize)
if err != nil {
return nil, err
}
payload = append(payload, framePayload[framePayloadSize:framePayloadSize+n]...)
framePayloadSize += n
if message.Kind == MessageTEXT {
// Verifying UTF-8
for verifyPos < len(payload) {
size := len(payload) - verifyPos
if _, err := utf8ToChar32Fixed(payload[verifyPos:], &size); err != nil {
if errors.Is(err, ErrShortUtf8) {
if !frame.fin {
savedLen := len(payload)
extendUnfinishedUtf8(&payload, verifyPos)
size = len(payload) - verifyPos
_, err := utf8ToChar32Fixed(payload[verifyPos:], &size)
if err != nil {
return nil, err
}
payload = payload[:savedLen]
break // Tolerating the unfinished UTF-8 sequences if the message is unfinished
}
return nil, err
} else {
return nil, err
}
}
verifyPos += size
}
}
}
if frame.fin {
break
}
}
}
message.Payload = payload
return &message, nil
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
// Client Handshake Errors
var ErrClientHandshakeBadResponse = errors.New("client handshake bad response")
var ErrClientHandshakeNoAccept = errors.New("client handshake no accept")
var ErrClientHandshakeDuplicateAccept = errors.New("client handshake duplicate accept")
var ErrClientHandshakeBadAccept = errors.New("client handshake bad accept")
// Server Handshake Errors
var ErrServerHandshakeBadRequest = errors.New("server handshake bad request")
var ErrServerHandshakeNoKey = errors.New("server handshake no key")
var ErrServerHandshakeDuplicateKey = errors.New("server handshake duplicate key")
// Connection Errors
var ErrCloseFrameSent = errors.New("close frame sent")
var ErrControlFrameTooBig = errors.New("control frame too big")
var ErrReservedBitsNotNegotiated = errors.New("reserved bits not negotiated")
var ErrUnexpectedOpCode = errors.New("unexpected opcode")
// utf-8 Errors
var ErrShortUtf8 = errors.New("short utf-8")
var ErrInvalidUtf8 = errors.New("invalid utf-8")
func headerMacro(header []byte, field string) byte {
switch field {
case "fin":
return (header[0] >> 7) & 0x1
case "rsv1":
return (header[0] >> 6) & 0x1
case "rsv2":
return (header[0] >> 5) & 0x1
case "rsv3":
return (header[0] >> 4) & 0x1
case "opcode":
return header[0] & 0xF
case "mask":
return header[1] >> 7
case "payload_len":
return header[1] & 0x7F
default:
panic("unreachable")
}
}
func computeSecWebSocketAccept(secWebSocketKey string) string {
h := sha1.New()
io.WriteString(h, secWebSocketKey+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func parseSecWebSocketKeyFromRequest(request *string) (string, error) {
foundSecWebSocketKey := false
var secWebSocketKey string
const lineSep = "\r\n"
const headerSep = ":"
// TODO: verify the request status line
if index := strings.Index(*request, lineSep); index != -1 {
*request = (*request)[index+len(lineSep):]
} else {
return "", ErrServerHandshakeBadRequest
}
// TODO: verify the rest of the headers of the request
// Right now we are only looking for Sec-WebSocket-Key
for len(*request) > 0 && !strings.HasPrefix(*request, lineSep) {
var header string
if index := strings.Index(*request, lineSep); index != -1 {
header = (*request)[0:index]
*request = (*request)[index+len(lineSep):]
} else {
return "", ErrServerHandshakeBadRequest
}
var key, value string
if index := strings.Index(header, headerSep); index != -1 {
key = strings.TrimSpace(header[0:index])
value = strings.TrimSpace(header[index+len(headerSep):])
} else {
return "", ErrServerHandshakeBadRequest
}
if key == "Sec-WebSocket-Key" {
if foundSecWebSocketKey {
return "", ErrServerHandshakeDuplicateKey
}
secWebSocketKey = value
foundSecWebSocketKey = true
}
}
if !strings.HasPrefix(*request, lineSep) {
return "", ErrServerHandshakeBadRequest
}
*request = (*request)[len(lineSep):]
if !foundSecWebSocketKey {
return "", ErrServerHandshakeNoKey
}
return secWebSocketKey, nil
}
func parseSecWebSocketAcceptFromResponse(response *string) (string, error) {
foundSecWebSocketAccept := false
var secWebSocketAccept string
const lineSep = "\r\n"
const headerSep = ":"
// TODO: verify the response status line
// If the status code is an error one, log the message
if index := strings.Index(*response, lineSep); index != -1 {
*response = (*response)[index+len(lineSep):]
} else {
return "", ErrClientHandshakeBadResponse
}
// TODO: verify the rest of the headers of the response
// Right now we are only looking for Sec-WebSocket-Accept
for len(*response) > 0 && !strings.HasPrefix(*response, lineSep) {
var header string
if index := strings.Index(*response, lineSep); index != -1 {
header = (*response)[0:index]
*response = (*response)[index+len(lineSep):]
} else {
return "", ErrClientHandshakeBadResponse
}
var key, value string
if index := strings.Index(header, headerSep); index != -1 {
key = strings.TrimSpace(header[0:index])
value = strings.TrimSpace(header[index+len(headerSep):])
} else {
return "", ErrClientHandshakeBadResponse
}
if key == "Sec-WebSocket-Accept" {
if foundSecWebSocketAccept {
return "", ErrClientHandshakeDuplicateAccept
}
secWebSocketAccept = value
foundSecWebSocketAccept = true
}
}
if !strings.HasPrefix(*response, lineSep) {
return "", ErrClientHandshakeBadResponse
}
*response = (*response)[len(lineSep):]
if !foundSecWebSocketAccept {
return "", ErrClientHandshakeNoAccept
}
return secWebSocketAccept, nil
}
type WSMessageKind byte
const MessageTEXT WSMessageKind = WSMessageKind(OpCodeTEXT)
const MessageBIN WSMessageKind = WSMessageKind(OpCodeBIN)
type WSMessage struct {
Kind WSMessageKind
Payload []byte
}
type WSOpcode byte
const (
OpCodeCONT WSOpcode = 0x0
OpCodeTEXT WSOpcode = 0x1
OpCodeBIN WSOpcode = 0x2
OpCodeCLOSE WSOpcode = 0x8
OpCodePING WSOpcode = 0x9
OpCodePONG WSOpcode = 0xA
)
func (opcode WSOpcode) name() string {
switch opcode {
case OpCodeCONT:
return "CONT"
case OpCodeTEXT:
return "TEXT"
case OpCodeBIN:
return "BIN"
case OpCodeCLOSE:
return "CLOSE"
case OpCodePING:
return "PING"
case OpCodePONG:
return "PONG"
default:
if 0x3 <= opcode && opcode <= 0x7 {
return fmt.Sprintf("NONCONTROL(0x%X)", opcode&0xF)
} else if 0xB <= opcode && opcode <= 0xF {
return fmt.Sprintf("CONTROL(0x%X)", opcode&0xF)
} else {
return fmt.Sprintf("INVALID(0x%X)", opcode&0xF)
}
}
}
func (opcode WSOpcode) isControl() bool {
return 0x8 <= opcode && opcode <= 0xF
}
type WSFrameHeader struct {
fin, rsv1, rsv2, rsv3 bool
opcode WSOpcode
masked bool
payloadLen int
mask [4]byte
}
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func itob(i uint8) bool {
return i != 0
}
func extendUnfinishedUtf8(payload *[]byte, pos int) {
c := (*payload)[pos]
var size int
if c&0x80 == 0 {
size = 1
} else if c&0xE0 == 0xC0 {
size = 2
} else if c&0xF0 == 0xE0 {
size = 3
} else {
size = 4
}
for len(*payload)-pos < size {
*payload = append(*payload, 0b1000_0000)
}
}
func utf8ToChar32Fixed(payload []byte, size *int) (rune, error) {
maxSize := *size
if maxSize < 1 {
return 0, ErrShortUtf8
}
c := payload[0]
if c&0x80 == 0 {
*size = 1
return rune(c), nil
}
if c&0xE0 == 0xC0 {
if maxSize < 2 {
return 0, ErrShortUtf8
}
*size = 2
uc := rune(c&0x1F) << 6
c = payload[1]
// Overlong sequence or invalid second.
if uc == 0 || c&0xC0 != 0x80 {
return 0, ErrInvalidUtf8
}
uc += rune(c & 0x3F)
// NEW: maximum overlong sequence
if uc <= 0b111_1111 {
return 0, ErrInvalidUtf8
}
// NEW: UTF-16 surrogate pairs
if 0xD800 <= uc && uc <= 0xDFFF {
return 0, ErrInvalidUtf8
}
return uc, nil
}
if c&0xF0 == 0xE0 {
if maxSize < 3 {
return 0, ErrShortUtf8
}
*size = 3
uc := rune(c&0x0F) << 12
c = payload[1]
// Overlong sequence or invalid last.
if c&0xC0 != 0x80 {
return 0, ErrInvalidUtf8
}
uc += rune(c&0x3F) << 6
c = payload[2]
if uc == 0 || c&0xC0 != 0x80 {
return 0, ErrInvalidUtf8
}
uc += rune(c & 0x3F)
// NEW: maximum overlong sequence
if uc <= 0b11111_111111 {
return 0, ErrInvalidUtf8
}
// NEW: UTF-16 surrogate pairs
if 0xD800 <= uc && uc <= 0xDFFF {
return 0, ErrInvalidUtf8
}
return uc, nil
}
if c&0xF0 == 0xF0 {
if maxSize < 4 {
return 0, ErrShortUtf8
}
if c&0xF8 != 0xF0 {
return 0, ErrInvalidUtf8
}
*size = 4
uc := rune(c&0x07) << 18
c = payload[1]
if c&0xC0 != 0x80 {
return 0, ErrInvalidUtf8
}
uc += rune(c&0x3F) << 12
c = payload[2]
if c&0xC0 != 0x80 {
return 0, ErrInvalidUtf8
}
uc += rune(c&0x3F) << 6
c = payload[3]
if uc == 0 || c&0xC0 != 0x80 {
return 0, ErrInvalidUtf8
}
uc += rune(c & 0x3F)
// NEW: UTF-16 surrogate pairs
if 0xD800 <= uc && uc <= 0xDFFF {
return 0, ErrInvalidUtf8
}
if uc <= 0b1111_111111_111111 {
return 0, ErrInvalidUtf8
}
if uc > 0x10FFFF {
return 0, ErrInvalidUtf8
}
return uc, nil
}
return 0, ErrInvalidUtf8
}