forked from hsiafan/httpdump
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_traffic_handler.go
510 lines (440 loc) · 12.3 KB
/
http_traffic_handler.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
package main
import (
"bytes"
"compress/gzip"
"compress/zlib"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"strconv"
"strings"
"time"
"github.com/hsiafan/glow/iox/filex"
"github.com/hsiafan/httpdump/httpport"
"bufio"
"github.com/google/gopacket/tcpassembly/tcpreader"
)
// ConnectionKey contains src and dst endpoint identify a connection
type ConnectionKey struct {
src Endpoint
dst Endpoint
}
func (ck *ConnectionKey) reverse() ConnectionKey {
return ConnectionKey{ck.dst, ck.src}
}
// return the src ip and port
func (ck *ConnectionKey) srcString() string {
return ck.src.String()
}
// return the dst ip and port
func (ck *ConnectionKey) dstString() string {
return ck.dst.String()
}
// HTTPConnectionHandler impl ConnectionHandler
type HTTPConnectionHandler struct {
option *Option
printer *Printer
}
func (handler *HTTPConnectionHandler) handle(src Endpoint, dst Endpoint, connection *TCPConnection) {
ck := ConnectionKey{src, dst}
trafficHandler := &HTTPTrafficHandler{
key: ck,
buffer: new(bytes.Buffer),
option: handler.option,
printer: handler.printer,
startTime: connection.lastTimestamp,
}
waitGroup.Add(1)
go trafficHandler.handle(connection)
}
func (handler *HTTPConnectionHandler) finish() {
//handler.printer.finish()
}
// HTTPTrafficHandler parse a http connection traffic and send to printer
type HTTPTrafficHandler struct {
startTime time.Time
endTime time.Time
key ConnectionKey
buffer *bytes.Buffer
option *Option
printer *Printer
}
// read http request/response stream, and do output
func (h *HTTPTrafficHandler) handle(connection *TCPConnection) {
defer waitGroup.Done()
defer connection.upStream.Close()
defer connection.downStream.Close()
// filter by args setting
requestReader := bufio.NewReader(connection.upStream)
defer discardAll(requestReader)
responseReader := bufio.NewReader(connection.downStream)
defer discardAll(responseReader)
for {
h.buffer = new(bytes.Buffer)
filtered := false
req, err := httpport.ReadRequest(requestReader)
h.startTime = connection.lastTimestamp
if err != nil {
if err != io.EOF {
logger.Warn("Error parsing HTTP requests:", err)
}
break
}
if h.option.Host != "" && !wildcardMatch(req.Host, h.option.Host) {
filtered = true
}
if h.option.Uri != "" && !wildcardMatch(req.RequestURI, h.option.Uri) {
filtered = true
}
// if is websocket request, by header: Upgrade: websocket
websocket := req.Header.Get("Upgrade") == "websocket"
expectContinue := req.Header.Get("Expect") == "100-continue"
resp, err := httpport.ReadResponse(responseReader, nil)
if err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
logger.Debug("Error parsing HTTP response: unexpected end, ", err, connection.clientID)
break
} else {
logger.Warn("Error parsing HTTP response:", err, connection.clientID)
}
if !filtered {
h.printRequest(req)
h.writeLine("")
h.printer.send(h.buffer.String())
} else {
discardAll(req.Body)
}
break
}
if h.option.StatusSet != nil && !h.option.StatusSet.Contains(resp.StatusCode) {
filtered = true
}
if !filtered {
h.printRequest(req)
h.writeLine("")
h.endTime = connection.lastTimestamp
h.printResponse(req.RequestURI, resp)
h.printer.send(h.buffer.String())
} else {
discardAll(req.Body)
discardAll(resp.Body)
}
if websocket {
if resp.StatusCode == 101 && resp.Header.Get("Upgrade") == "websocket" {
// change to handle websocket
h.handleWebsocket(requestReader, responseReader)
break
}
}
if expectContinue {
if resp.StatusCode == 100 {
// read next response, the real response
resp, err := httpport.ReadResponse(responseReader, nil)
if err == io.EOF {
logger.Warn("Error parsing HTTP requests: unexpected end, ", err)
break
}
if err == io.ErrUnexpectedEOF {
logger.Warn("Error parsing HTTP requests: unexpected end, ", err)
// here return directly too, to avoid error when long polling connection is used
break
}
if err != nil {
logger.Warn("Error parsing HTTP response:", err, connection.clientID)
break
}
if !filtered {
h.printResponse(req.RequestURI, resp)
h.printer.send(h.buffer.String())
} else {
discardAll(resp.Body)
}
} else if resp.StatusCode == 417 {
}
}
}
h.printer.send(h.buffer.String())
}
func (h *HTTPTrafficHandler) handleWebsocket(requestReader *bufio.Reader, responseReader *bufio.Reader) {
//TODO: websocket
}
func (h *HTTPTrafficHandler) writeLineFormat(format string, a ...interface{}) {
fmt.Fprintf(h.buffer, format, a...)
}
func (h *HTTPTrafficHandler) write(a ...interface{}) {
fmt.Fprint(h.buffer, a...)
}
func (h *HTTPTrafficHandler) writeLine(a ...interface{}) {
fmt.Fprintln(h.buffer, a...)
}
func (h *HTTPTrafficHandler) printRequestMark() {
h.writeLine()
}
func (h *HTTPTrafficHandler) printHeader(header httpport.Header) {
for name, values := range header {
for _, value := range values {
h.writeLine(name+":", value)
}
}
}
// print http request
func (h *HTTPTrafficHandler) printRequest(req *httpport.Request) {
defer discardAll(req.Body)
if h.option.Curl {
h.printCurlRequest(req)
} else {
h.printNormalRequest(req)
}
}
var blockHeaders = map[string]bool{
"Content-Length": true,
"Transfer-Encoding": true,
"Connection": true,
"Accept-Encoding:": true,
}
// print http request curl command
func (h *HTTPTrafficHandler) printCurlRequest(req *httpport.Request) {
//TODO: expect-100 continue handle
h.writeLine()
h.writeLine(strings.Repeat("*", 10), " REQUEST ", h.key.srcString(), " -----> ", h.key.dstString(), " // ", h.startTime.Format(time.RFC3339Nano))
h.writeLineFormat("curl -X %v http://%v%v \\\n", req.Method, h.key.dstString(), req.RequestURI)
var reader io.ReadCloser
var deCompressed bool
if h.option.DumpBody {
reader = req.Body
deCompressed = false
} else {
reader, deCompressed = h.tryDecompress(req.Header, req.Body)
}
if deCompressed {
defer reader.Close()
}
seq := 0
for name, values := range req.Header {
seq++
if blockHeaders[name] {
continue
}
if deCompressed {
if name == "Content-Encoding" {
continue
}
}
for idx, value := range values {
if seq == len(req.Header) && idx == len(values)-1 {
h.writeLineFormat(" -H '%v: %v'\n", name, value)
} else {
h.writeLineFormat(" -H '%v: %v' \\\n", name, value)
}
}
}
if req.ContentLength == 0 || req.Method == "GET" || req.Method == "HEAD" || req.Method == "TRACE" ||
req.Method == "OPTIONS" {
h.writeLine()
return
}
if h.option.DumpBody {
filename := "request-" + uriToFileName(req.RequestURI, h.startTime)
h.writeLineFormat(" -d '@%v'", filename)
err := filex.WriteAllFromReader(filename, reader)
if err != nil {
h.writeLine("dump to file failed:", err)
}
} else {
br := bufio.NewReader(reader)
// optimize for one line body
firstLine, err := br.ReadString('\n')
if err != nil && err != io.EOF {
// read error
} else if err == io.EOF && !strings.Contains(firstLine, "'") {
h.writeLineFormat(" -d '%v'", strconv.Quote(firstLine))
} else {
h.writeLineFormat(" -d @- << HTTP_DUMP_BODY_EOF\n")
h.write(firstLine)
for {
line, err := br.ReadString('\n')
if err != nil && err != io.EOF {
break
}
h.write(line)
if err == io.EOF {
h.writeLine("\nHTTP_DUMP_BODY_EOF")
break
}
}
}
}
h.writeLine()
}
// print http request
func (h *HTTPTrafficHandler) printNormalRequest(req *httpport.Request) {
//TODO: expect-100 continue handle
if h.option.Level == "url" {
h.writeLine(req.Method, req.Host+req.RequestURI)
return
}
h.writeLine()
h.writeLine(strings.Repeat("*", 10), " REQUEST ", h.key.srcString(), " -----> ", h.key.dstString(), " // ", h.startTime.Format(time.RFC3339Nano))
h.writeLine(req.Method, req.RequestURI, req.Proto)
h.printHeader(req.Header)
var hasBody = true
if req.ContentLength == 0 || req.Method == "GET" || req.Method == "HEAD" || req.Method == "TRACE" ||
req.Method == "OPTIONS" {
hasBody = false
}
if h.option.DumpBody {
filename := "request-" + uriToFileName(req.RequestURI, h.startTime)
h.writeLine("\n// dump body to file:", filename)
err := filex.WriteAllFromReader(filename, req.Body)
if err != nil {
h.writeLine("dump to file failed:", err)
}
return
}
if h.option.Level == "header" {
if hasBody {
h.writeLine("\n// body size:", discardAll(req.Body),
", set [level = all] to display http body")
}
return
}
h.writeLine()
if hasBody {
h.printBody(req.Header, req.Body)
}
}
// print http response
func (h *HTTPTrafficHandler) printResponse(uri string, resp *httpport.Response) {
defer discardAll(resp.Body)
if h.option.Level == "url" {
return
}
h.writeLine(strings.Repeat("*", 10), " RESPONSE ", h.key.srcString(), " <----- ", h.key.dstString(), " // ", h.startTime.Format(time.RFC3339Nano), "-", h.endTime.Format(time.RFC3339Nano), "=", h.endTime.Sub(h.startTime).String())
h.writeLine(resp.StatusLine)
for _, header := range resp.RawHeaders {
h.writeLine(header)
}
var hasBody = true
if resp.ContentLength == 0 || resp.StatusCode == 304 || resp.StatusCode == 204 {
hasBody = false
}
if h.option.DumpBody {
filename := "response-" + uriToFileName(uri, h.startTime)
h.writeLine("\n// dump body to file:", filename)
err := filex.WriteAllFromReader(filename, resp.Body)
if err != nil {
h.writeLine("dump to file failed:", err)
}
return
}
if h.option.Level == "header" {
if hasBody {
h.writeLine("\n// body size:", discardAll(resp.Body),
", set [level = all] to display http body")
}
return
}
h.writeLine()
if hasBody {
h.printBody(resp.Header, resp.Body)
}
}
func (h *HTTPTrafficHandler) tryDecompress(header httpport.Header, reader io.ReadCloser) (io.ReadCloser, bool) {
contentEncoding := header.Get("Content-Encoding")
var nr io.ReadCloser
var err error
if contentEncoding == "" {
// do nothing
return reader, false
} else if strings.Contains(contentEncoding, "gzip") {
nr, err = gzip.NewReader(reader)
if err != nil {
return reader, false
}
return nr, true
} else if strings.Contains(contentEncoding, "deflate") {
nr, err = zlib.NewReader(reader)
if err != nil {
return reader, false
}
return nr, true
} else {
return reader, false
}
}
// print http request/response body
func (h *HTTPTrafficHandler) printBody(header httpport.Header, reader io.ReadCloser) {
// deal with content encoding such as gzip, deflate
nr, decompressed := h.tryDecompress(header, reader)
if decompressed {
defer nr.Close()
}
// check mime type and charset
contentType := header.Get("Content-Type")
if contentType == "" {
// TODO: detect content type using httpport.DetectContentType()
}
mimeTypeStr, charset := parseContentType(contentType)
var mimeType = parseMimeType(mimeTypeStr)
isText := mimeType.isTextContent()
isBinary := mimeType.isBinaryContent()
if !isText {
err := h.printNonTextTypeBody(nr, contentType, isBinary)
if err != nil {
h.writeLine("{Read content error", err, "}")
}
return
}
var body string
var err error
if charset == "" {
// response do not set charset, try to detect
var data []byte
data, err := ioutil.ReadAll(nr)
if err == nil {
// TODO: try to detect charset
body = string(data)
}
} else {
body, err = readToStringWithCharset(nr, charset)
}
if err != nil {
h.writeLine("{Read body failed", err, "}")
return
}
// prettify json
if mimeType.subType == "json" || likeJSON(body) {
var jsonValue interface{}
_ = json.Unmarshal([]byte(body), &jsonValue)
prettyJSON, err := json.MarshalIndent(jsonValue, "", " ")
if err == nil {
body = string(prettyJSON)
}
}
h.writeLine(body)
h.writeLine()
}
func (h *HTTPTrafficHandler) printNonTextTypeBody(reader io.Reader, contentType string, isBinary bool) error {
if h.option.Force && !isBinary {
data, err := ioutil.ReadAll(reader)
if err != nil {
return err
}
// TODO: try to detect charset
str := string(data)
h.writeLine(str)
h.writeLine()
} else {
h.writeLine("{Non-text body, content-type:", contentType, ", len:", discardAll(reader), "}")
}
return nil
}
func discardAll(r io.Reader) (dicarded int) {
return tcpreader.DiscardBytesToEOF(r)
}
func uriToFileName(uri string, t time.Time) string {
timeStr := t.Format("2006_01_02_15_04_05.000000")
filename := strings.ReplaceAll(uri, "/", "_") + "-" + timeStr
return filename[1:]
}