/
polling.go
405 lines (344 loc) 路 9.34 KB
/
polling.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
package transports
import (
"compress/flate"
"compress/gzip"
"io"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/andybalholm/brotli"
"github.com/zishang520/engine.io-go-parser/packet"
_types "github.com/zishang520/engine.io-go-parser/types"
"github.com/zishang520/engine.io/events"
"github.com/zishang520/engine.io/log"
"github.com/zishang520/engine.io/types"
"github.com/zishang520/engine.io/utils"
)
var polling_log = log.NewLog("engine:polling")
type polling struct {
*transport
dataCtx *types.HttpContext
mu_dataCtx sync.RWMutex
shouldClose types.Callable
mu_shouldClose sync.RWMutex
}
// HTTP polling New.
func NewPolling(ctx *types.HttpContext) *polling {
p := &polling{}
return p.New(ctx)
}
func (p *polling) New(ctx *types.HttpContext) *polling {
p.transport = &transport{}
p.supportsFraming = false
// Transport name
p.name = "polling"
p.transport.New(ctx)
p.onClose = p.PollingOnClose
p.onData = p.PollingOnData
p.doWrite = p.PollingDoWrite
p.doClose = p.PollingDoClose
p.send = p.PollingSend
p.closeTimeout = 30 * 1000 * time.Millisecond
return p
}
// Overrides onRequest.
func (p *polling) OnRequest(ctx *types.HttpContext) {
method := ctx.Method()
if http.MethodGet == method {
p.onPollRequest(ctx)
} else if http.MethodPost == method {
p.onDataRequest(ctx)
} else {
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.Write(nil)
}
}
// The client sends a request awaiting for us to send data.
func (p *polling) onPollRequest(ctx *types.HttpContext) {
p.mu_req.RLock()
if p.req != nil {
defer p.mu_req.RUnlock()
polling_log.Debug("request overlap")
// assert: p.res, '.req should be (un)set together'
p.OnError("overlap from client", nil)
ctx.SetStatusCode(http.StatusBadRequest)
ctx.Write(nil)
return
}
p.mu_req.RUnlock()
polling_log.Debug("setting request")
onClose := events.Listener(func(...any) {
p.OnError("poll connection closed prematurely", nil)
})
p.mu_req.Lock()
p.req = ctx
p.mu_req.Unlock()
ctx.Cleanup = func() {
ctx.RemoveListener("close", onClose)
p.mu_req.Lock()
p.req = nil
p.mu_req.Unlock()
}
ctx.On("close", onClose)
p.SetWritable(true)
p.Emit("drain")
p.mu_shouldClose.RLock()
// if we're still writable but had a pending close, trigger an empty send
if p.Writable() && p.shouldClose != nil {
polling_log.Debug("triggering empty send to append close packet")
p.Send([]*packet.Packet{
{
Type: packet.NOOP,
},
})
}
p.mu_shouldClose.RUnlock()
}
// The client sends a request with data.
func (p *polling) onDataRequest(ctx *types.HttpContext) {
p.mu_dataCtx.RLock()
if p.dataCtx != nil {
defer p.mu_dataCtx.RUnlock()
// assert: p.dataRes, '.dataCtx should be (un)set together'
p.OnError("data request overlap from client", nil)
ctx.SetStatusCode(http.StatusBadRequest)
ctx.Write(nil)
return
}
p.mu_dataCtx.RUnlock()
isBinary := "application/octet-stream" == ctx.Headers().Peek("Content-Type")
if isBinary && p.protocol == 4 {
p.OnError("invalid content", nil)
return
}
p.mu_dataCtx.Lock()
p.dataCtx = ctx
p.mu_dataCtx.Unlock()
var onClose events.Listener
cleanup := func() {
ctx.RemoveListener("close", onClose)
p.mu_dataCtx.Lock()
p.dataCtx = nil
p.mu_dataCtx.Unlock()
}
onClose = func(...any) {
cleanup()
p.OnError("data request connection closed prematurely", nil)
}
ctx.On("close", onClose)
if ctx.Request().ContentLength > p.maxHttpBufferSize {
ctx.SetStatusCode(http.StatusRequestEntityTooLarge)
ctx.Write(nil)
cleanup()
return
}
var packet _types.BufferInterface
if isBinary {
packet = _types.NewBytesBuffer(nil)
} else {
packet = _types.NewStringBuffer(nil)
}
if rc, ok := ctx.Request().Body.(io.ReadCloser); ok && rc != nil {
packet.ReadFrom(rc)
rc.Close()
}
p.OnData(packet)
headers := utils.NewParameterBag(map[string][]string{
// text/html is required instead of text/plain to avoid an
// unwanted download dialog on certain user-agents (GH-43)
"Content-Type": {"text/html"},
"Content-Length": {"2"},
})
// After writing the data, close will be triggered, so it needs to be executed first.
cleanup()
// The following process in nodejs is asynchronous.
ctx.ResponseHeaders.With(p.Headers(ctx, headers).All())
ctx.SetStatusCode(http.StatusOK)
io.WriteString(ctx, "ok")
}
// Processes the incoming data payload.
func (p *polling) PollingOnData(data _types.BufferInterface) {
polling_log.Debug(`received "%s"`, data)
packets, _ := p.parser.DecodePayload(data)
for _, packetData := range packets {
if packet.CLOSE == packetData.Type {
polling_log.Debug("got xhr close packet")
p.OnClose()
return
}
p.OnPacket(packetData)
}
}
// Overrides onClose.
func (p *polling) PollingOnClose() {
if p.Writable() {
// close pending poll request
p.Send([]*packet.Packet{
{
Type: packet.NOOP,
},
})
}
p.TransportOnClose()
}
// Writes a packet payload.
func (p *polling) PollingSend(packets []*packet.Packet) {
p.musend.Lock()
defer p.musend.Unlock()
p.mu_req.RLock()
ctx := p.req
p.mu_req.RUnlock()
if ctx == nil {
return
}
p.SetWritable(false)
p.mu_shouldClose.Lock()
if p.shouldClose != nil {
polling_log.Debug("appending close packet to payload")
packets = append(packets, &packet.Packet{
Type: packet.CLOSE,
})
p.shouldClose()
p.shouldClose = nil
}
p.mu_shouldClose.Unlock()
option := &packet.Options{Compress: false}
for _, packetData := range packets {
if packetData.Options != nil && packetData.Options.Compress {
option.Compress = true
break
}
}
if p.protocol == 3 {
data, _ := p.parser.EncodePayload(packets, p.supportsBinary)
p.write(ctx, data, option)
} else {
data, _ := p.parser.EncodePayload(packets)
p.write(ctx, data, option)
}
}
// Writes data as response to poll request.
func (p *polling) write(ctx *types.HttpContext, data _types.BufferInterface, options *packet.Options) {
polling_log.Debug(`writing "%s"`, data)
p.DoWrite(ctx, data, options, func(ctx *types.HttpContext) { ctx.Cleanup() })
}
// Performs the write.
func (p *polling) PollingDoWrite(ctx *types.HttpContext, data _types.BufferInterface, options *packet.Options, callback func(*types.HttpContext)) {
contentType := "application/octet-stream"
// explicit UTF-8 is required for pages not served under utf
switch data.(type) {
case *_types.StringBuffer:
contentType = "text/plain; charset=UTF-8"
}
headers := utils.NewParameterBag(map[string][]string{
"Content-Type": {contentType},
})
respond := func(data _types.BufferInterface, length string) {
headers.Set("Content-Length", length)
ctx.ResponseHeaders.With(p.Headers(ctx, headers).All())
ctx.SetStatusCode(http.StatusOK)
io.Copy(ctx, data)
callback(ctx)
}
if p.httpCompression == nil || options == nil || !options.Compress {
respond(data, strconv.Itoa(data.Len()))
return
}
if data.Len() < p.httpCompression.Threshold {
respond(data, strconv.Itoa(data.Len()))
return
}
encoding := utils.Contains(ctx.Headers().Peek("Accept-Encoding"), []string{"gzip", "deflate", "br"})
if encoding == "" {
respond(data, strconv.Itoa(data.Len()))
return
}
if buf, err := p.compress(data, encoding); err == nil {
headers.Set("Content-Encoding", encoding)
respond(buf, strconv.Itoa(buf.Len()))
}
}
// Compresses data.
func (p *polling) compress(data _types.BufferInterface, encoding string) (_types.BufferInterface, error) {
polling_log.Debug("compressing")
buf := _types.NewBytesBuffer(nil)
switch encoding {
case "gzip":
gz, err := gzip.NewWriterLevel(buf, 1)
if err != nil {
return nil, err
}
defer gz.Close()
if _, err := io.Copy(gz, data); err != nil {
return nil, err
}
case "deflate":
fl, err := flate.NewWriter(buf, 1)
if err != nil {
return nil, err
}
defer fl.Close()
if _, err := io.Copy(fl, data); err != nil {
return nil, err
}
case "br":
br := brotli.NewWriterLevel(buf, 1)
defer br.Close()
if _, err := io.Copy(br, data); err != nil {
return nil, err
}
}
return buf, nil
}
// Closes the transport.
func (p *polling) PollingDoClose(fn ...types.Callable) {
polling_log.Debug("closing")
p.mu_dataCtx.RLock()
dataCtx := p.dataCtx
p.mu_dataCtx.RUnlock()
if dataCtx != nil && !dataCtx.IsDone() {
polling_log.Debug("aborting ongoing data request")
dataCtx.ResponseHeaders.Set("Connection", "close")
dataCtx.SetStatusCode(http.StatusTooManyRequests)
dataCtx.Write(nil)
}
onClose := func() {
if len(fn) > 0 {
(fn[0])()
}
p.OnClose()
}
if p.Writable() {
polling_log.Debug("transport writable - closing right away")
p.Send([]*packet.Packet{
{
Type: packet.CLOSE,
},
})
onClose()
} else if p.GetDiscarded() {
polling_log.Debug("transport discarded - closing right away")
onClose()
} else {
polling_log.Debug("transport not writable - buffering orderly close")
closeTimeoutTimer := utils.SetTimeOut(onClose, p.closeTimeout)
p.mu_shouldClose.Lock()
p.shouldClose = func() {
utils.ClearTimeout(closeTimeoutTimer)
onClose()
}
p.mu_shouldClose.Unlock()
}
}
// Returns headers for a response.
func (p *polling) Headers(ctx *types.HttpContext, headers *utils.ParameterBag) *utils.ParameterBag {
// prevent XSS warnings on IE
// https://github.com/socketio/socket.io/pull/1333
if ua := ctx.UserAgent(); (len(ua) > 0) && ((strings.Index(ua, ";MSIE") > -1) || (strings.Index(ua, "Trident/") > -1)) {
headers.Set("X-XSS-Protection", "0")
}
p.Emit("headers", headers, ctx)
return headers
}