-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
372 lines (300 loc) · 7.76 KB
/
client.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
package webgockets
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"slices"
"strings"
)
type Client struct {
c *http.Client
wsURL *url.URL
httpURL *url.URL
socket io.ReadWriteCloser
frames chan frame
// fragmented indicates that the current frames being received is fragmented.
fragmented bool
// closeErr is set as soon as a close frame has been received.
// It's needed since we want to be able to return the same close error everywhere.
closeErr ErrClose
}
// NewClient validates the wsURL and creates a new Client.
func NewClient(wsURL string) (*Client, error) {
u, err := validateURL(wsURL)
if err != nil {
return nil, fmt.Errorf("invalid url: %w", err)
}
httpURL := u
if u.Scheme == "ws" {
httpURL.Scheme = "http"
} else {
httpURL.Scheme = "https"
}
client := &Client{
c: http.DefaultClient,
wsURL: u,
httpURL: httpURL,
frames: make(chan frame, 100), // TODO: Can most likely just have this as blocking.
}
return client, nil
}
// Connect handshakes and starts receiving messages.
func (c *Client) Connect() error {
w, err := c.handshake()
if err != nil {
return fmt.Errorf("failed to handshake: %w", err)
}
c.socket = w
go func() {
err = c.readHandler()
}()
return err
}
func (c *Client) handshake() (io.ReadWriteCloser, error) {
req, err := http.NewRequest("GET", c.httpURL.String(), nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Add("Upgrade", "websocket")
req.Header.Add("Connection", "Upgrade")
key, err := handshakeKeyRequest()
if err != nil {
return nil, err
}
req.Header.Add("Sec-Websocket-Key", key)
req.Header.Add("Sec-WebSocket-Protocol", "chat, superchat")
req.Header.Add("Sec-WebSocket-Version", "13")
resp, err := c.c.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send handshake request: %w", err)
}
if resp.StatusCode != 101 {
return nil, fmt.Errorf("unexpected status code %d", resp.StatusCode)
}
expectedAcceptKey, err := handshakeAcceptKey(key)
if err != nil {
return nil, err
}
expectedHeaders := map[string]string{
"Upgrade": "websocket",
"Connection": "upgrade",
}
for header, value := range expectedHeaders {
h := strings.ToLower(resp.Header.Get(header))
if h != value {
return nil, fmt.Errorf("unexpected header %s: %s, wanted %s", header, h, value)
}
}
// Case sensitive.
expectedExactHeaders := map[string]string{
"Sec-Websocket-Accept": expectedAcceptKey,
}
for header, value := range expectedExactHeaders {
h := resp.Header.Get(header)
if h != value {
return nil, fmt.Errorf("unexpected header %s: %s, wanted %s", header, h, value)
}
}
w, ok := resp.Body.(io.ReadWriteCloser)
if !ok {
return nil, fmt.Errorf("wasn't able to make body a writer")
}
return w, nil
}
func (c *Client) ReadString(ctx context.Context) (string, error) {
bs, err := c.Read(ctx)
return string(bs), err
}
// Read reads a non-fragmented frame, or concatenates the payload of multiple fragmented frames.
func (c *Client) Read(ctx context.Context) ([]byte, error) {
payload, _, err := c.read(ctx)
return payload, err
}
func (c *Client) read(ctx context.Context) ([]byte, OpCode, error) {
frame, err := c.getFrame(ctx)
if err != nil {
return nil, 0, err
}
payload := frame.Payload
opcode := frame.Opcode
for !frame.Fin {
frame, err = c.getFrame(ctx)
if err != nil {
return nil, 0, err
}
payload = append(payload, frame.Payload...)
}
return payload, opcode, nil
}
func (c *Client) getFrame(ctx context.Context) (frame, error) {
select {
case <-ctx.Done():
return frame{}, ctx.Err()
case f, ok := <-c.frames:
if !ok {
return frame{}, &c.closeErr
}
for f.IsControl() {
if err := c.controlHandler(f); err != nil {
return frame{}, err
}
if f.Opcode == OpcodeConnectionClose {
c.closeErr = ErrClose{Code: f.CloseStatusCode, Payload: string(f.Payload)}
return frame{}, &c.closeErr
}
f, ok = <-c.frames
if !ok {
return frame{}, &c.closeErr
}
}
return f, nil
}
}
func (c *Client) readHandler() error {
for {
frame, err := c.readFrame()
if err != nil {
return c.Close()
}
if frame.IsControl() {
if err := c.controlHandler(frame); errors.Is(err, io.EOF) {
return nil
} else if err != nil {
return fmt.Errorf("failed to handle control frame: %w", err)
}
continue
}
c.frames <- frame
}
}
func (c *Client) readFrame() (frame, error) {
f, err := parseFrame(c.socket, c.fragmented)
if errors.Is(err, errInvalidFrame) {
return frame{}, errInvalidFrame
} else if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
return frame{}, io.EOF
}
return frame{}, err
}
// Fragmentation done if Fin is set.
if !f.IsControl() {
c.fragmented = !f.Fin
}
return f, nil
}
type ErrClose struct {
Code uint16
Payload string
}
func (e *ErrClose) Error() string {
return fmt.Sprintf("%d: %s", e.Code, e.Payload)
}
func (c *Client) controlHandler(frame frame) error {
switch frame.Opcode {
case OpcodePong:
// Do nothing.
case OpcodePing:
return c.sendPong(frame.Payload)
case OpcodeConnectionClose:
c.closeErr.Code = frame.CloseStatusCode
c.closeErr.Payload = string(frame.Payload)
return c.sendClose(frame.CloseStatusCode)
default:
return fmt.Errorf("unknown op code %d", frame.Opcode)
}
return nil
}
func (c *Client) sendPong(payload []byte) error {
frame := frame{
Fin: true,
Opcode: OpcodePong,
IsMask: true,
Payload: payload,
}
bs, err := frame.ToBytes()
if err != nil {
return fmt.Errorf("failed to make frame bytes: %w", err)
}
if _, err := c.socket.Write(bs); err != nil {
return fmt.Errorf("failed to write bytes: %w", err)
}
return nil
}
var validBasicCloseCodes = []uint16{1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011}
func isValidCloseCode(code uint16) bool {
if slices.Contains(validBasicCloseCodes, code) {
return true
}
return code >= 3000 && code <= 4999
}
func (c *Client) sendClose(statusCode uint16) error {
if !isValidCloseCode(statusCode) {
statusCode = 1002
}
frame := frame{
Fin: true,
Opcode: OpcodeConnectionClose,
CloseStatusCode: statusCode,
IsMask: true,
Payload: []byte("Going away"),
}
bs, err := frame.ToBytes()
if err != nil {
return fmt.Errorf("failed to make frame bytes: %w", err)
}
if _, err := c.socket.Write(bs); err != nil {
return fmt.Errorf("failed to write bytes: %w", err)
}
return nil
}
func (c *Client) WriteString(str string) (int, error) {
return c.Write([]byte(str))
}
// Write writes a text frame.
func (c *Client) Write(bs []byte) (int, error) {
return c.write(bs, OpcodeTextFrame)
}
// WriteJSON writes a text frame with marshaled bytes from the given json struct.
func (c *Client) WriteJSON(jsonData any) (int, error) {
bs, err := json.Marshal(jsonData)
if err != nil {
return 0, fmt.Errorf("invalid json: %w", err)
}
return c.Write(bs)
}
// WriteBinary writes a binary frame
func (c *Client) WriteBinary(bs []byte) (int, error) {
return c.write(bs, OpcodeBinaryFrame)
}
func (c *Client) write(bs []byte, opCode OpCode) (int, error) {
if opCode != OpcodeBinaryFrame && opCode != OpcodeTextFrame {
return 0, fmt.Errorf("invalid op code")
}
frameBs, err := frame{
Fin: true,
Opcode: opCode,
IsMask: true,
PayloadLength: uint(len(bs)),
Payload: bs,
}.ToBytes()
if err != nil {
return 0, fmt.Errorf("failed to make frame bytes: %w", err)
}
n, err := c.socket.Write(frameBs)
if err != nil && strings.Contains(err.Error(), "use of closed network connection") {
return n, &c.closeErr
}
return 0, err
}
func (c *Client) Close() error {
if err := c.socket.Close(); err != nil {
return fmt.Errorf("failed to close connection: %w", err)
}
close(c.frames)
return nil
}