-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_parser.go
564 lines (491 loc) · 14.2 KB
/
http_parser.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
package http
import (
"bytes"
"errors"
"fmt"
"time"
"unicode"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/common/streambuf"
"github.com/elastic/beats/libbeat/logp"
)
// Http Message
type message struct {
ts time.Time
hasContentLength bool
headerOffset int
version version
connection common.NetString
chunkedLength int
chunkedBody []byte
isRequest bool
tcpTuple common.TCPTuple
cmdlineTuple *common.CmdlineTuple
direction uint8
//Request Info
requestURI common.NetString
method common.NetString
statusCode uint16
statusPhrase common.NetString
realIP common.NetString
// Http Headers
contentLength int
contentType common.NetString
transferEncoding common.NetString
headers map[string]common.NetString
size uint64
//Raw Data
raw []byte
notes []string
//Offsets
start int
end int
bodyOffset int
next *message
}
type version struct {
major uint8
minor uint8
}
type parser struct {
config *parserConfig
}
type parserConfig struct {
realIPHeader string
sendHeaders bool
sendAllHeaders bool
headersWhitelist map[string]bool
}
var (
transferEncodingChunked = []byte("chunked")
constCRLF = []byte("\r\n")
constClose = []byte("close")
constKeepAlive = []byte("keep-alive")
constHTTPVersion = []byte("HTTP/")
nameContentLength = []byte("content-length")
nameContentType = []byte("content-type")
nameTransferEncoding = []byte("transfer-encoding")
nameConnection = []byte("connection")
)
func newParser(config *parserConfig) *parser {
return &parser{config: config}
}
func (parser *parser) parse(s *stream, extraMsgSize int) (bool, bool) {
m := s.message
if extraMsgSize > 0 {
// A packet of extraMsgSize size was seen, but we don't have
// its actual bytes. This is only usable in the `stateBody` state.
if s.parseState != stateBody {
return false, false
}
return parser.eatBody(s, m, extraMsgSize)
}
for s.parseOffset < len(s.data) {
switch s.parseState {
case stateStart:
if cont, ok, complete := parser.parseHTTPLine(s, m); !cont {
return ok, complete
}
case stateHeaders:
if cont, ok, complete := parser.parseHeaders(s, m); !cont {
return ok, complete
}
case stateBody:
return parser.parseBody(s, m)
case stateBodyChunkedStart:
if cont, ok, complete := parser.parseBodyChunkedStart(s, m); !cont {
return ok, complete
}
case stateBodyChunked:
if cont, ok, complete := parser.parseBodyChunked(s, m); !cont {
return ok, complete
}
case stateBodyChunkedWaitFinalCRLF:
return parser.parseBodyChunkedWaitFinalCRLF(s, m)
}
}
return true, false
}
func (*parser) parseHTTPLine(s *stream, m *message) (cont, ok, complete bool) {
m.start = s.parseOffset
i := bytes.Index(s.data[s.parseOffset:], []byte("\r\n"))
if i == -1 {
return false, true, false
}
// Very basic tests on the first line. Just to check that
// we have what looks as an HTTP message
var version []byte
var err error
fline := s.data[s.parseOffset:i]
if len(fline) < 9 {
if isDebug {
debugf("First line too small")
}
return false, false, false
}
if bytes.Equal(fline[0:5], constHTTPVersion) {
//RESPONSE
m.isRequest = false
version = fline[5:8]
m.statusCode, m.statusPhrase, err = parseResponseStatus(fline[9:])
if err != nil {
logp.Warn("Failed to understand HTTP response status: %s", fline[9:])
return false, false, false
}
if isDebug {
debugf("HTTP status_code=%d, status_phrase=%s", m.statusCode, m.statusPhrase)
}
} else {
// REQUEST
afterMethodIdx := bytes.IndexFunc(fline, unicode.IsSpace)
afterRequestURIIdx := bytes.LastIndexFunc(fline, unicode.IsSpace)
// Make sure we have the VERB + URI + HTTP_VERSION
if afterMethodIdx == -1 || afterRequestURIIdx == -1 || afterMethodIdx == afterRequestURIIdx {
if isDebug {
debugf("Couldn't understand HTTP request: %s", fline)
}
return false, false, false
}
m.method = common.NetString(fline[:afterMethodIdx])
m.requestURI = common.NetString(fline[afterMethodIdx+1 : afterRequestURIIdx])
if bytes.Equal(fline[afterRequestURIIdx+1:afterRequestURIIdx+len(constHTTPVersion)+1], constHTTPVersion) {
m.isRequest = true
version = fline[afterRequestURIIdx+len(constHTTPVersion)+1:]
} else {
if isDebug {
debugf("Couldn't understand HTTP version: %s", fline)
}
return false, false, false
}
}
m.version.major, m.version.minor, err = parseVersion(version)
if err != nil {
if isDebug {
debugf("Failed to understand HTTP version: %v", version)
}
m.version.major = 1
m.version.minor = 0
}
if isDebug {
debugf("HTTP version %d.%d", m.version.major, m.version.minor)
}
// ok so far
s.parseOffset = i + 2
m.headerOffset = s.parseOffset
s.parseState = stateHeaders
return true, true, true
}
func parseResponseStatus(s []byte) (uint16, []byte, error) {
if isDebug {
debugf("parseResponseStatus: %s", s)
}
var phrase []byte
p := bytes.IndexByte(s, ' ')
if p == -1 {
p = len(s)
} else {
phrase = s[p+1:]
}
statusCode, err := parseInt(s[0:p])
if err != nil {
return 0, nil, fmt.Errorf("Unable to parse status code from [%s]", s)
}
return uint16(statusCode), phrase, nil
}
func parseVersion(s []byte) (uint8, uint8, error) {
if len(s) < 3 {
return 0, 0, errors.New("Invalid version")
}
major := s[0] - '0'
minor := s[2] - '0'
if major > 1 || minor > 2 {
return 0, 0, errors.New("unsupported version")
}
return uint8(major), uint8(minor), nil
}
func (parser *parser) parseHeaders(s *stream, m *message) (cont, ok, complete bool) {
if len(s.data)-s.parseOffset >= 2 &&
bytes.Equal(s.data[s.parseOffset:s.parseOffset+2], []byte("\r\n")) {
// EOH
s.parseOffset += 2
m.bodyOffset = s.parseOffset
if !m.isRequest && ((100 <= m.statusCode && m.statusCode < 200) || m.statusCode == 204 || m.statusCode == 304) {
//response with a 1xx, 204 , or 304 status code is always terminated
// by the first empty line after the header fields
if isDebug {
debugf("Terminate response, status code %d", m.statusCode)
}
m.end = s.parseOffset
m.size = uint64(m.end - m.start)
return false, true, true
}
if bytes.Equal(m.transferEncoding, transferEncodingChunked) {
// support for HTTP/1.1 Chunked transfer
// Transfer-Encoding overrides the Content-Length
if isDebug {
debugf("Read chunked body")
}
s.parseState = stateBodyChunkedStart
return true, true, true
}
if m.contentLength == 0 && (m.isRequest || m.hasContentLength) {
if isDebug {
debugf("Empty content length, ignore body")
}
// Ignore body for request that contains a message body but not a Content-Length
m.end = s.parseOffset
m.size = uint64(m.end - m.start)
return false, true, true
}
if isDebug {
debugf("Read body")
}
s.parseState = stateBody
} else {
ok, hfcomplete, offset := parser.parseHeader(m, s.data[s.parseOffset:])
if !ok {
return false, false, false
}
if !hfcomplete {
return false, true, false
}
s.parseOffset += offset
}
return true, true, true
}
func (parser *parser) parseHeader(m *message, data []byte) (bool, bool, int) {
if m.headers == nil {
m.headers = make(map[string]common.NetString)
}
i := bytes.Index(data, []byte(":"))
if i == -1 {
// Expected \":\" in headers. Assuming incomplete"
return true, false, 0
}
config := parser.config
// enabled if required. Allocs for parameters slow down parser big times
if isDetailed {
detailedf("Data: %s", data)
detailedf("Header: %s", data[:i])
}
// skip folding line
for p := i + 1; p < len(data); {
q := bytes.Index(data[p:], constCRLF)
if q == -1 {
// Assuming incomplete
return true, false, 0
}
p += q
if len(data) > p && (data[p+1] == ' ' || data[p+1] == '\t') {
p = p + 2
} else {
var headerNameBuf [140]byte
headerName := toLower(headerNameBuf[:], data[:i])
headerVal := trim(data[i+1 : p])
if isDebug {
debugf("Header: '%s' Value: '%s'\n", data[:i], headerVal)
}
// Headers we need for parsing. Make sure we always
// capture their value
if bytes.Equal(headerName, nameContentLength) {
m.contentLength, _ = parseInt(headerVal)
m.hasContentLength = true
} else if bytes.Equal(headerName, nameContentType) {
m.contentType = headerVal
} else if bytes.Equal(headerName, nameTransferEncoding) {
m.transferEncoding = common.NetString(headerVal)
} else if bytes.Equal(headerName, nameConnection) {
m.connection = headerVal
}
if len(config.realIPHeader) > 0 && bytes.Equal(headerName, []byte(config.realIPHeader)) {
if ips := bytes.SplitN(headerVal, []byte{','}, 2); len(ips) > 0 {
m.realIP = trim(ips[0])
}
}
if config.sendHeaders {
if !config.sendAllHeaders {
_, exists := config.headersWhitelist[string(headerName)]
if !exists {
return true, true, p + 2
}
}
if val, ok := m.headers[string(headerName)]; ok {
composed := make([]byte, len(val)+len(headerVal)+2)
off := copy(composed, val)
copy(composed[off:], []byte(", "))
copy(composed[off+2:], headerVal)
m.headers[string(headerName)] = composed
} else {
m.headers[string(headerName)] = headerVal
}
}
return true, true, p + 2
}
}
return true, false, len(data)
}
func (*parser) parseBody(s *stream, m *message) (ok, complete bool) {
if isDebug {
debugf("parseBody body: %d", s.parseOffset)
}
if !m.hasContentLength && (bytes.Equal(m.connection, constClose) ||
(isVersion(m.version, 1, 0) && !bytes.Equal(m.connection, constKeepAlive))) {
// HTTP/1.0 no content length. Add until the end of the connection
if isDebug {
debugf("http conn close, received %d", len(s.data)-s.parseOffset)
}
s.bodyReceived += (len(s.data) - s.parseOffset)
m.contentLength += (len(s.data) - s.parseOffset)
s.parseOffset = len(s.data)
return true, false
} else if len(s.data[s.parseOffset:]) >= m.contentLength-s.bodyReceived {
s.parseOffset += (m.contentLength - s.bodyReceived)
m.end = s.parseOffset
m.size = uint64(m.end - m.start)
return true, true
} else {
s.bodyReceived += (len(s.data) - s.parseOffset)
s.parseOffset = len(s.data)
if isDebug {
debugf("bodyReceived: %d", s.bodyReceived)
}
return true, false
}
}
// eatBody acts as if size bytes were received, without having access to
// those bytes.
func (*parser) eatBody(s *stream, m *message, size int) (ok, complete bool) {
if isDebug {
debugf("eatBody body: %d", s.parseOffset)
}
if !m.hasContentLength && (bytes.Equal(m.connection, constClose) ||
(isVersion(m.version, 1, 0) && !bytes.Equal(m.connection, constKeepAlive))) {
// HTTP/1.0 no content length. Add until the end of the connection
if isDebug {
debugf("http conn close, received %d", size)
}
s.bodyReceived += size
m.contentLength += size
return true, false
} else if size >= m.contentLength-s.bodyReceived {
s.bodyReceived += (m.contentLength - s.bodyReceived)
m.end = s.parseOffset
m.size = uint64(m.bodyOffset-m.start) + uint64(m.contentLength)
return true, true
} else {
s.bodyReceived += size
if isDebug {
debugf("bodyReceived: %d", s.bodyReceived)
}
return true, false
}
}
func (*parser) parseBodyChunkedStart(s *stream, m *message) (cont, ok, complete bool) {
// read hexa length
i := bytes.Index(s.data[s.parseOffset:], constCRLF)
if i == -1 {
return false, true, false
}
line := string(s.data[s.parseOffset : s.parseOffset+i])
_, err := fmt.Sscanf(line, "%x", &m.chunkedLength)
if err != nil {
logp.Warn("Failed to understand chunked body start line")
return false, false, false
}
s.parseOffset += i + 2 //+ \r\n
if m.chunkedLength == 0 {
if len(s.data[s.parseOffset:]) < 2 {
s.parseState = stateBodyChunkedWaitFinalCRLF
return false, true, false
}
if s.data[s.parseOffset] != '\r' || s.data[s.parseOffset+1] != '\n' {
logp.Warn("Expected CRLF sequence at end of message")
return false, false, false
}
s.parseOffset += 2 // skip final CRLF
m.end = s.parseOffset
m.size = uint64(m.end - m.start)
return false, true, true
}
s.bodyReceived = 0
s.parseState = stateBodyChunked
return true, true, false
}
func (*parser) parseBodyChunked(s *stream, m *message) (cont, ok, complete bool) {
if len(s.data[s.parseOffset:]) >= m.chunkedLength-s.bodyReceived+2 /*\r\n*/ {
// Received more data than expected
m.chunkedBody = append(m.chunkedBody, s.data[s.parseOffset:s.parseOffset+m.chunkedLength-s.bodyReceived]...)
s.parseOffset += (m.chunkedLength - s.bodyReceived + 2 /*\r\n*/)
m.contentLength += m.chunkedLength
s.parseState = stateBodyChunkedStart
return true, true, false
}
if len(s.data[s.parseOffset:]) >= m.chunkedLength-s.bodyReceived {
// we need need to wait for the +2, else we can crash on next call
return false, true, false
}
// Received less data than expected
m.chunkedBody = append(m.chunkedBody, s.data[s.parseOffset:]...)
s.bodyReceived += (len(s.data) - s.parseOffset)
s.parseOffset = len(s.data)
return false, true, false
}
func (*parser) parseBodyChunkedWaitFinalCRLF(s *stream, m *message) (ok, complete bool) {
if len(s.data[s.parseOffset:]) < 2 {
return true, false
}
if s.data[s.parseOffset] != '\r' || s.data[s.parseOffset+1] != '\n' {
logp.Warn("Expected CRLF sequence at end of message")
return false, false
}
s.parseOffset += 2 // skip final CRLF
m.end = s.parseOffset
m.size = uint64(m.end - m.start)
return true, true
}
func isVersion(v version, major, minor uint8) bool {
return v.major == major && v.minor == minor
}
func trim(buf []byte) []byte {
return trimLeft(trimRight(buf))
}
func trimLeft(buf []byte) []byte {
for i, b := range buf {
if b != ' ' && b != '\t' {
return buf[i:]
}
}
return nil
}
func trimRight(buf []byte) []byte {
for i := len(buf) - 1; i > 0; i-- {
b := buf[i]
if b != ' ' && b != '\t' {
return buf[:i+1]
}
}
return nil
}
func parseInt(line []byte) (int, error) {
buf := streambuf.NewFixed(line)
i, err := buf.IntASCII(false)
return int(i), err
// TODO: is it an error if 'buf.Len() != 0 {}' ?
}
func toLower(buf, in []byte) []byte {
if len(in) > len(buf) {
goto unbufferedToLower
}
for i, b := range in {
if b > 127 {
goto unbufferedToLower
}
if 'A' <= b && b <= 'Z' {
b = b - 'A' + 'a'
}
buf[i] = b
}
return buf[:len(in)]
unbufferedToLower:
return bytes.ToLower(in)
}