HTTP协议解码重组响应包时解析错误,如何将buf指针恢复到调用前的状态。
1. 运行环境
win11
go version go1.17.1 windows/amd64
2. 问题描述?
最近在学习协议解码,想要利用go语言重组一条流中的http请求和响应。目前的demo是根据gopacket官方给出的例子进行更改的.(github.com/google/gopacket/blob/ma... )
主要修改了第57行的解析原理,但是运行时会出现部分http响应解析不了。根据调试分析,是在http.ReadRequest(buf)调用后buf的窗口后移,导致解析错误
line 29:
var filter = flag.String("f", "tcp", "BPF filter for pcap")
line 57:
func (h *httpStream) run() {
buf := bufio.NewReader(&h.r)
for {
//last_h := h
req, err := http.ReadRequest(buf)
if err != nil {
buf.Reset(&h.r) //尝试恢复buf所指向的数据
rsp, err := http.ReadResponse(buf, nil)
if err != nil {
log.Println("Error reading stream", h.net, h.transport, ":", err)
} else {
bodyBytes := tcpreader.DiscardBytesToEOF(rsp.Body)
rsp.Body.Close()
log.Println("Received response from stream", h.net, h.transport, ":", rsp, "with", bodyBytes, "bytes in response body")
}
} else {
bodyBytes := tcpreader.DiscardBytesToEOF(req.Body)
req.Body.Close()
log.Println("Received request from stream", h.net, h.transport, ":", req, "with", bodyBytes, "bytes in request body")
continue
}
}
}
标红的这一段解析错误,然后直接跳到下一段进行解析,没有恢复相关数据。
3. 您期望得到的结果?
正常解析HTTP请求和响应。
4. 您实际得到的结果?
标红部分解析失败