-
Notifications
You must be signed in to change notification settings - Fork 94
/
upgrader.go
359 lines (321 loc) · 10.6 KB
/
upgrader.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
package gws
import (
"bufio"
"bytes"
"crypto/tls"
"errors"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/lxzan/gws/internal"
)
type responseWriter struct {
// 错误信息
// Error information
err error
// 字节缓冲区
// Byte buffer
b *bytes.Buffer
// 子协议
// Subprotocol
subprotocol string
}
// Init 初始化
// Initializes the responseWriter struct
func (c *responseWriter) Init() *responseWriter {
c.b = binaryPool.Get(512)
c.b.WriteString("HTTP/1.1 101 Switching Protocols\r\n")
c.b.WriteString("Upgrade: websocket\r\n")
c.b.WriteString("Connection: Upgrade\r\n")
return c
}
// Close 回收资源
// Recycling resources
func (c *responseWriter) Close() {
binaryPool.Put(c.b)
c.b = nil
}
// WithHeader 添加 HTTP Header
// Adds an http header
func (c *responseWriter) WithHeader(k, v string) {
c.b.WriteString(k)
c.b.WriteString(": ")
c.b.WriteString(v)
c.b.WriteString("\r\n")
}
// WithExtraHeader 添加额外的 HTTP Header
// Adds extra http header
func (c *responseWriter) WithExtraHeader(h http.Header) {
for k, _ := range h {
c.WithHeader(k, h.Get(k))
}
}
// WithSubProtocol 根据请求头和预期的子协议列表设置子协议
// Sets the subprotocol based on the request header and the expected subprotocols list
func (c *responseWriter) WithSubProtocol(requestHeader http.Header, expectedSubProtocols []string) {
if len(expectedSubProtocols) > 0 {
c.subprotocol = internal.GetIntersectionElem(expectedSubProtocols, internal.Split(requestHeader.Get(internal.SecWebSocketProtocol.Key), ","))
if c.subprotocol == "" {
c.err = ErrSubprotocolNegotiation
return
}
c.WithHeader(internal.SecWebSocketProtocol.Key, c.subprotocol)
}
}
// Write 将缓冲区内容写入连接,并设置超时
// Writes the buffer content to the connection and sets the timeout
func (c *responseWriter) Write(conn net.Conn, timeout time.Duration) error {
if c.err != nil {
return c.err
}
c.b.WriteString("\r\n")
if err := conn.SetDeadline(time.Now().Add(timeout)); err != nil {
return err
}
if _, err := c.b.WriteTo(conn); err != nil {
return err
}
return conn.SetDeadline(time.Time{})
}
type Upgrader struct {
option *ServerOption
deflaterPool *deflaterPool
eventHandler Event
}
// NewUpgrader 创建一个新的 Upgrader 实例
// Creates a new instance of Upgrader
func NewUpgrader(eventHandler Event, option *ServerOption) *Upgrader {
u := &Upgrader{
option: initServerOption(option),
eventHandler: eventHandler,
deflaterPool: new(deflaterPool),
}
if u.option.PermessageDeflate.Enabled {
u.deflaterPool.initialize(u.option.PermessageDeflate, option.ReadMaxPayloadSize)
}
return u
}
// 劫持 HTTP 连接并返回底层的网络连接和缓冲读取器
// Hijacks the HTTP connection and returns the underlying network connection and buffered reader
func (c *Upgrader) hijack(w http.ResponseWriter) (net.Conn, *bufio.Reader, error) {
hj, ok := w.(http.Hijacker)
if !ok {
return nil, nil, internal.CloseInternalErr
}
netConn, _, err := hj.Hijack()
if err != nil {
return nil, nil, err
}
br := c.option.config.brPool.Get()
br.Reset(netConn)
return netConn, br, nil
}
// 根据客户端和服务器的扩展协商结果获取 PermessageDeflate 配置
// Gets the PermessageDeflate configuration based on the negotiation results between the client and server extensions
func (c *Upgrader) getPermessageDeflate(extensions string) PermessageDeflate {
clientPD := permessageNegotiation(extensions)
serverPD := c.option.PermessageDeflate
pd := PermessageDeflate{
Enabled: serverPD.Enabled && strings.Contains(extensions, internal.PermessageDeflate),
Threshold: serverPD.Threshold,
Level: serverPD.Level,
PoolSize: serverPD.PoolSize,
ServerContextTakeover: clientPD.ServerContextTakeover && serverPD.ServerContextTakeover,
ClientContextTakeover: clientPD.ClientContextTakeover && serverPD.ClientContextTakeover,
ServerMaxWindowBits: serverPD.ServerMaxWindowBits,
ClientMaxWindowBits: serverPD.ClientMaxWindowBits,
}
pd.setThreshold(true)
return pd
}
// Upgrade 升级 HTTP 连接到 WebSocket 连接
// Upgrades the HTTP connection to a WebSocket connection
func (c *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request) (*Conn, error) {
netConn, br, err := c.hijack(w)
if err != nil {
return nil, err
}
return c.UpgradeFromConn(netConn, br, r)
}
// UpgradeFromConn 从现有的网络连接升级到 WebSocket 连接
// Upgrades from an existing network connection to a WebSocket connection
func (c *Upgrader) UpgradeFromConn(conn net.Conn, br *bufio.Reader, r *http.Request) (*Conn, error) {
socket, err := c.doUpgradeFromConn(conn, br, r)
if err != nil {
_ = c.writeErr(conn, err)
_ = conn.Close()
}
return socket, err
}
// 向客户端写入 HTTP 错误响应
// Writes an HTTP error response to the client
func (c *Upgrader) writeErr(conn net.Conn, err error) error {
var str = err.Error()
var buf = binaryPool.Get(256)
buf.WriteString("HTTP/1.1 400 Bad Request\r\n")
buf.WriteString("Date: " + time.Now().Format(time.RFC1123) + "\r\n")
buf.WriteString("Content-Length: " + strconv.Itoa(len(str)) + "\r\n")
buf.WriteString("Content-Type: text/plain; charset=utf-8\r\n")
buf.WriteString("\r\n")
buf.WriteString(str)
_, result := buf.WriteTo(conn)
binaryPool.Put(buf)
return result
}
// 从现有的网络连接升级到 WebSocket 连接
// Upgrades from an existing network connection to a WebSocket connection
func (c *Upgrader) doUpgradeFromConn(netConn net.Conn, br *bufio.Reader, r *http.Request) (*Conn, error) {
// 授权请求,如果授权失败,返回未授权错误
// Authorize the request, if authorization fails, return an unauthorized error
var session = c.option.NewSession()
if !c.option.Authorize(r, session) {
return nil, ErrUnauthorized
}
// 检查请求头
// check request headers
if r.Method != http.MethodGet {
return nil, ErrHandshake
}
if !strings.EqualFold(r.Header.Get(internal.SecWebSocketVersion.Key), internal.SecWebSocketVersion.Val) {
return nil, errors.New("gws: websocket version not supported")
}
if !internal.HttpHeaderContains(r.Header.Get(internal.Connection.Key), internal.Connection.Val) {
return nil, ErrHandshake
}
if !strings.EqualFold(r.Header.Get(internal.Upgrade.Key), internal.Upgrade.Val) {
return nil, ErrHandshake
}
var rw = new(responseWriter).Init()
defer rw.Close()
var extensions = r.Header.Get(internal.SecWebSocketExtensions.Key)
var pd = c.getPermessageDeflate(extensions)
if pd.Enabled {
rw.WithHeader(internal.SecWebSocketExtensions.Key, pd.genResponseHeader())
}
var websocketKey = r.Header.Get(internal.SecWebSocketKey.Key)
if websocketKey == "" {
return nil, ErrHandshake
}
rw.WithHeader(internal.SecWebSocketAccept.Key, internal.ComputeAcceptKey(websocketKey))
rw.WithSubProtocol(r.Header, c.option.SubProtocols)
rw.WithExtraHeader(c.option.ResponseHeader)
if err := rw.Write(netConn, c.option.HandshakeTimeout); err != nil {
return nil, err
}
config := c.option.getConfig()
socket := &Conn{
ss: session,
isServer: true,
subprotocol: rw.subprotocol,
pd: pd,
conn: netConn,
config: config,
br: br,
continuationFrame: continuationFrame{},
fh: frameHeader{},
handler: c.eventHandler,
closed: 0,
writeQueue: workerQueue{maxConcurrency: 1},
readQueue: make(channel, c.option.ParallelGolimit),
}
// 压缩字典和解压字典内存开销比较大, 故使用懒加载
// Compressing and decompressing dictionaries has a large memory overhead, so use lazy loading.
if pd.Enabled {
socket.deflater = c.deflaterPool.Select()
if pd.ServerContextTakeover {
socket.cpsWindow.initialize(config.cswPool, pd.ServerMaxWindowBits)
}
if pd.ClientContextTakeover {
socket.dpsWindow.initialize(config.dswPool, pd.ClientMaxWindowBits)
}
}
return socket, nil
}
// Server WebSocket服务器
// Websocket server
type Server struct {
// 升级器,用于将 HTTP 连接升级到 WebSocket 连接
// Upgrader, used to upgrade HTTP connections to WebSocket connections
upgrader *Upgrader
// 服务器选项配置
// Server option configuration
option *ServerOption
// 错误处理回调函数
// Error handling callback function
OnError func(conn net.Conn, err error)
// 请求处理回调函数
// Request handling callback function
OnRequest func(conn net.Conn, br *bufio.Reader, r *http.Request)
}
// NewServer 创建一个新的 WebSocket 服务器实例
// Creates a new WebSocket server instance
func NewServer(eventHandler Event, option *ServerOption) *Server {
var c = &Server{upgrader: NewUpgrader(eventHandler, option)}
c.option = c.upgrader.option
c.OnError = func(conn net.Conn, err error) { c.option.Logger.Error("gws: " + err.Error()) }
c.OnRequest = func(conn net.Conn, br *bufio.Reader, r *http.Request) {
socket, err := c.GetUpgrader().UpgradeFromConn(conn, br, r)
if err != nil {
c.OnError(conn, err)
} else {
socket.ReadLoop()
}
}
return c
}
// GetUpgrader 获取服务器的升级器实例
// Retrieves the upgrader instance of the server
func (c *Server) GetUpgrader() *Upgrader {
return c.upgrader
}
// Run 启动 WebSocket 服务器,监听指定地址
// Starts the WebSocket server and listens on the specified address
func (c *Server) Run(addr string) error {
listener, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return c.RunListener(listener)
}
// RunTLS 启动支持 TLS 的 WebSocket 服务器,监听指定地址
// Starts the WebSocket server with TLS support and listens on the specified address
func (c *Server) RunTLS(addr string, certFile, keyFile string) error {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
if c.option.TlsConfig == nil {
c.option.TlsConfig = &tls.Config{}
}
config := c.option.TlsConfig.Clone()
config.Certificates = []tls.Certificate{cert}
config.NextProtos = []string{"http/1.1"}
listener, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return c.RunListener(tls.NewListener(listener, config))
}
// RunListener 使用指定的监听器运行 WebSocket 服务器
// Runs the WebSocket server using the specified listener
func (c *Server) RunListener(listener net.Listener) error {
defer listener.Close()
for {
netConn, err := listener.Accept()
if err != nil {
c.OnError(netConn, err)
continue
}
go func(conn net.Conn) {
br := c.option.config.brPool.Get()
br.Reset(conn)
if r, err := http.ReadRequest(br); err != nil {
c.OnError(conn, err)
} else {
c.OnRequest(conn, br, r)
}
}(netConn)
}
}