-
Notifications
You must be signed in to change notification settings - Fork 5
/
client.go
296 lines (255 loc) · 6.61 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
// Copyright 2021-2024 antlabs. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package quickws
import (
"bufio"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/antlabs/wsutil/bufio2"
"github.com/antlabs/wsutil/bytespool"
"github.com/antlabs/wsutil/deflate"
"github.com/antlabs/wsutil/enum"
"github.com/antlabs/wsutil/fixedreader"
"github.com/antlabs/wsutil/hostname"
)
var (
defaultTimeout = time.Minute * 30
)
type DialOption struct {
Header http.Header
u *url.URL
tlsConfig *tls.Config
dialTimeout time.Duration
bindClientHttpHeader *http.Header // 握手成功之后, 客户端获取http.Header,
Config
}
func ClientOptionToConf(opts ...ClientOption) *DialOption {
var dial DialOption
if err := dial.defaultSetting(); err != nil {
panic(err.Error())
}
for _, o := range opts {
o(&dial)
}
return &dial
}
func DialConf(rawUrl string, conf *DialOption) (*Conn, error) {
u, err := url.Parse(rawUrl)
if err != nil {
return nil, err
}
conf.u = u
conf.dialTimeout = defaultTimeout
if conf.Header == nil {
conf.Header = make(http.Header)
}
return conf.Dial()
}
// https://datatracker.ietf.org/doc/html/rfc6455#section-4.1
// 又是一顿if else, 咬文嚼字
func Dial(rawUrl string, opts ...ClientOption) (*Conn, error) {
var dial DialOption
u, err := url.Parse(rawUrl)
if err != nil {
return nil, err
}
dial.u = u
dial.dialTimeout = defaultTimeout
if dial.Header == nil {
dial.Header = make(http.Header)
}
if err := dial.defaultSetting(); err != nil {
return nil, err
}
for _, o := range opts {
o(&dial)
}
return dial.Dial()
}
// 准备握手的数据
func (d *DialOption) handshake() (*http.Request, string, error) {
switch {
case d.u.Scheme == "wss":
d.u.Scheme = "https"
case d.u.Scheme == "ws":
d.u.Scheme = "http"
default:
return nil, "", fmt.Errorf("Unknown scheme, only supports ws:// or wss://: got %s", d.u.Scheme)
}
// 满足4.1
// 第2点 GET约束http 1.1版本约束
req, err := http.NewRequest("GET", d.u.String(), nil)
if err != nil {
return nil, "", err
}
// 第5点
d.Header.Add("Upgrade", "websocket")
// 第6点
d.Header.Add("Connection", "Upgrade")
// 第7点
secWebSocket := secWebSocketAccept()
d.Header.Add("Sec-WebSocket-Key", secWebSocket)
// TODO 第8点
// 第9点
d.Header.Add("Sec-WebSocket-Version", "13")
if d.Decompression && d.Compression {
// d.Header.Add("Sec-WebSocket-Extensions", genSecWebSocketExtensions(d.Pd))
d.Header.Add("Sec-WebSocket-Extensions", deflate.GenSecWebSocketExtensions(d.PermessageDeflateConf))
}
if len(d.subProtocols) > 0 {
d.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.subProtocols, ", ")}
}
req.Header = d.Header
return req, secWebSocket, nil
}
// 检查服务端响应的数据
// 4.2.2.5
func (d *DialOption) validateRsp(rsp *http.Response, secWebSocket string) error {
if rsp.StatusCode != 101 {
return fmt.Errorf("%w %d", ErrWrongStatusCode, rsp.StatusCode)
}
// 第2点
if !strings.EqualFold(rsp.Header.Get("Upgrade"), "websocket") {
return ErrUpgradeFieldValue
}
// 第3点
if !strings.EqualFold(rsp.Header.Get("Connection"), "Upgrade") {
return ErrConnectionFieldValue
}
// 第4点
if !strings.EqualFold(rsp.Header.Get("Sec-WebSocket-Accept"), secWebSocketAcceptVal(secWebSocket)) {
return ErrSecWebSocketAccept
}
// TODO 5点
// TODO 6点
return nil
}
// wss已经修改为https
func (d *DialOption) tlsConn(c net.Conn) net.Conn {
if d.u.Scheme == "https" {
cfg := d.tlsConfig
if cfg == nil {
cfg = &tls.Config{}
} else {
cfg = cfg.Clone()
}
if cfg.ServerName == "" {
host := d.u.Host
if pos := strings.Index(host, ":"); pos != -1 {
host = host[:pos]
}
cfg.ServerName = host
}
return tls.Client(c, cfg)
}
return c
}
func (d *DialOption) Dial() (wsCon *Conn, err error) {
// scheme ws -> http
// scheme wss -> https
req, secWebSocket, err := d.handshake()
if err != nil {
return nil, err
}
var conn net.Conn
hostName := hostname.GetHostName(d.u)
dialFunc := net.DialTimeout
if d.dialFunc != nil {
dialInterface, err := d.dialFunc()
if err != nil {
return nil, err
}
dialFunc = func(network, address string, timeout time.Duration) (net.Conn, error) {
return dialInterface.Dial(network, address)
}
}
if d.proxyFunc != nil {
proxyURL, err := d.proxyFunc(req)
if err != nil {
return nil, err
}
dialFunc = newhttpProxy(proxyURL, dialFunc).DialTimeout
}
conn, err = dialFunc("tcp", hostName, d.dialTimeout)
if err != nil {
return nil, err
}
conn = d.tlsConn(conn)
defer func() {
if err != nil && conn != nil {
conn.Close()
conn = nil
}
}()
err = conn.SetDeadline(time.Time{})
if err = req.Write(conn); err != nil {
return
}
br := bufio.NewReader(bufio.NewReader(conn))
rsp, err := http.ReadResponse(br, req)
if err != nil {
return nil, err
}
if d.bindClientHttpHeader != nil {
*d.bindClientHttpHeader = rsp.Header.Clone()
}
pd, err := deflate.GetConnPermessageDeflate(rsp.Header)
if err != nil {
return nil, err
}
if d.Decompression {
pd.Decompression = pd.Enable && d.Decompression
}
if d.Compression {
pd.Compression = pd.Enable && d.Compression
}
if err = d.validateRsp(rsp, secWebSocket); err != nil {
return
}
// 处理下已经在bufio里面的数据,后面都是直接操作net.Conn,所以需要取出bufio里面已读取的数据
var fr fixedreader.FixedReader
if d.parseMode == ParseModeWindows {
fr.Init(conn, bytespool.GetBytes(1024+enum.MaxFrameHeaderSize))
if br.Buffered() > 0 {
b, err := br.Peek(br.Buffered())
if err != nil {
return nil, err
}
buf := fr.BufPtr()
if len(b) > 1024+enum.MaxFrameHeaderSize {
bytespool.PutBytes(buf)
buf = bytespool.GetBytes(len(b) + enum.MaxFrameHeaderSize)
fr.Reset(buf)
}
copy(*buf, b)
fr.W = len(b)
}
bufio2.ClearReader(br)
br = nil
}
if err := conn.SetDeadline(time.Time{}); err != nil {
return nil, err
}
if wsCon, err = newConn(conn, true /* client is true*/, &d.Config, fr, br); err != nil {
return nil, err
}
wsCon.pd = pd
wsCon.Callback = d.cb
return wsCon, nil
}