-
Notifications
You must be signed in to change notification settings - Fork 13
/
client.go
247 lines (200 loc) · 5.39 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
package websocket
import (
"bufio"
"bytes"
"crypto/rand"
"crypto/tls"
"errors"
"net"
"time"
"github.com/valyala/fasthttp"
)
var (
// ErrCannotUpgrade shows up when an error occurred when upgrading a connection.
ErrCannotUpgrade = errors.New("cannot upgrade connection")
)
// MakeClient returns Conn using an existing connection.
//
// url must be a complete URL format i.e. http://localhost:8080/ws
func MakeClient(c net.Conn, url string) (*Client, error) {
return client(c, url, nil)
}
// ClientWithHeaders returns a Conn using an existing connection and sending custom headers.
func ClientWithHeaders(c net.Conn, url string, req *fasthttp.Request) (*Client, error) {
return client(c, url, req)
}
// UpgradeAsClient will upgrade the connection as a client
//
// This function should be used with connections that intend to use a
// plain framing.
//
// r can be nil.
func UpgradeAsClient(c net.Conn, url string, r *fasthttp.Request) error {
req := fasthttp.AcquireRequest()
res := fasthttp.AcquireResponse()
uri := fasthttp.AcquireURI()
defer fasthttp.ReleaseRequest(req)
defer fasthttp.ReleaseResponse(res)
defer fasthttp.ReleaseURI(uri)
uri.Update(url)
origin := bytePool.Get().([]byte)
key := bytePool.Get().([]byte)
defer bytePool.Put(origin)
defer bytePool.Put(key)
origin = prepareOrigin(origin, uri)
key = makeRandKey(key[:0])
if r != nil {
r.CopyTo(req)
}
req.Header.SetMethod("GET")
req.Header.AddBytesKV(originString, origin)
req.Header.AddBytesKV(connectionString, upgradeString)
req.Header.AddBytesKV(upgradeString, websocketString)
req.Header.AddBytesKV(wsHeaderVersion, supportedVersions[0])
req.Header.AddBytesKV(wsHeaderKey, key)
// TODO: Add compression
req.SetRequestURIBytes(uri.FullURI())
br := bufio.NewReader(c)
bw := bufio.NewWriter(c)
req.Write(bw)
bw.Flush()
err := res.Read(br)
if err == nil {
if res.StatusCode() != 101 ||
!equalsFold(res.Header.PeekBytes(upgradeString), websocketString) {
err = ErrCannotUpgrade
}
}
return err
}
func client(c net.Conn, url string, r *fasthttp.Request) (cl *Client, err error) {
err = UpgradeAsClient(c, url, r)
if err == nil {
cl = &Client{
c: c,
brw: bufio.NewReadWriter(
bufio.NewReader(c), bufio.NewWriter(c)),
}
}
return cl, err
}
// Dial establishes a websocket connection as client.
//
// url parameter must follow the WebSocket URL format i.e. ws://host:port/path
func Dial(url string) (*Client, error) {
cnf := &tls.Config{
InsecureSkipVerify: false,
MinVersion: tls.VersionTLS11,
MaxVersion: tls.VersionTLS13,
}
return dial(url, cnf, nil)
}
// DialTLS establishes a websocket connection as client with the
// tls.Config. The config will be used if the URL is wss:// like.
func DialTLS(url string, cnf *tls.Config) (*Client, error) {
return dial(url, cnf, nil)
}
// DialWithHeaders establishes a websocket connection as client sending a personalized request.
func DialWithHeaders(url string, req *fasthttp.Request) (*Client, error) {
cnf := &tls.Config{
InsecureSkipVerify: false,
MinVersion: tls.VersionTLS11,
}
return dial(url, cnf, req)
}
func dial(url string, cnf *tls.Config, req *fasthttp.Request) (conn *Client, err error) {
uri := fasthttp.AcquireURI()
defer fasthttp.ReleaseURI(uri)
uri.Update(url)
scheme := "https"
port := ":443"
if bytes.Equal(uri.Scheme(), wsString) {
scheme, port = "http", ":80"
}
uri.SetScheme(scheme)
addr := bytePool.Get().([]byte)
defer bytePool.Put(addr)
addr = append(addr[:0], uri.Host()...)
if n := bytes.LastIndexByte(addr, ':'); n == -1 {
addr = append(addr, port...)
}
var c net.Conn
if scheme == "http" {
c, err = net.Dial("tcp", b2s(addr))
} else {
c, err = tls.Dial("tcp", b2s(addr), cnf)
}
if err == nil {
conn, err = client(c, uri.String(), req)
if err != nil {
c.Close()
}
}
return conn, err
}
func makeRandKey(b []byte) []byte {
b = extendByteSlice(b, 16)
rand.Read(b[:16])
b = appendEncode(base64, b[:0], b[:16])
return b
}
// Client holds a WebSocket connection.
//
// The client is NOT concurrently safe. It is intended to be
// used with the Frame struct.
type Client struct {
c net.Conn
brw *bufio.ReadWriter
}
// Write writes the content `b` as text.
//
// To send binary content use WriteBinary.
func (c *Client) Write(b []byte) (int, error) {
fr := AcquireFrame()
defer ReleaseFrame(fr)
fr.SetFin()
fr.SetPayload(b)
fr.SetText()
fr.Mask()
return c.WriteFrame(fr)
}
// WriteBinary writes the content `b` as binary.
//
// To send text content use Write.
func (c *Client) WriteBinary(b []byte) (int, error) {
fr := AcquireFrame()
defer ReleaseFrame(fr)
fr.SetFin()
fr.SetPayload(b)
fr.SetBinary()
fr.Mask()
return c.WriteFrame(fr)
}
// WriteFrame writes the frame into the WebSocket connection.
func (c *Client) WriteFrame(fr *Frame) (int, error) {
nn, err := fr.WriteTo(c.brw)
if err == nil {
err = c.brw.Flush()
}
return int(nn), err
}
// ReadFrame reads a frame from the connection.
func (c *Client) ReadFrame(fr *Frame) (int, error) {
n, err := fr.ReadFrom(c.brw)
return int(n), err
}
// Close gracefully closes the websocket connection.
func (c *Client) Close() error {
fr := AcquireFrame()
fr.SetClose()
fr.SetFin()
fr.SetStatus(StatusNone)
_, err := c.WriteFrame(fr)
if err != nil {
return err
}
c.c.SetReadDeadline(time.Now().Add(time.Second * 3)) // wait 3 seconds before closing
// just read the next message
c.ReadFrame(fr)
return c.c.Close()
}