Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

write status first then hijack #126

Merged
merged 1 commit into from
Jan 15, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 8 additions & 30 deletions forwardproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -573,45 +573,23 @@ func serveHiddenPage(w http.ResponseWriter, authErr error) error {
// Hijacks the connection from ResponseWriter, writes the response and proxies data between targetConn
// and hijacked connection.
func serveHijack(w http.ResponseWriter, targetConn net.Conn) error {
clientConn, bufReader, err := http.NewResponseController(w).Hijack()
w.WriteHeader(http.StatusOK)
clientConn, brw, err := http.NewResponseController(w).Hijack()
if err != nil {
return caddyhttp.Error(http.StatusInternalServerError,
fmt.Errorf("hijack failed: %v", err))
}
defer clientConn.Close()
// bufReader may contain unprocessed buffered data from the client.
if bufReader != nil {
// snippet borrowed from `proxy` plugin
if n := bufReader.Reader.Buffered(); n > 0 {
rbuf, err := bufReader.Reader.Peek(n)
if err != nil {
return caddyhttp.Error(http.StatusBadGateway, err)
}
_, _ = targetConn.Write(rbuf)

}
}
// Since we hijacked the connection, we lost the ability to write and flush headers via w.
// Let's handcraft the response and send it manually.
res := &http.Response{
StatusCode: http.StatusOK,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: make(http.Header),
}
res.Header.Set("Server", "Caddy")

buf := bufio.NewWriter(clientConn)
err = res.Write(buf)
if err != nil {
return caddyhttp.Error(http.StatusInternalServerError,
fmt.Errorf("failed to write response: %v", err))
// snippet borrowed from `proxy` plugin
if n := brw.Reader.Buffered(); n > 0 {
rbuf, _ := brw.Peek(n)
_, _ = targetConn.Write(rbuf)
}
err = buf.Flush()
err = brw.Flush()
if err != nil {
return caddyhttp.Error(http.StatusInternalServerError,
fmt.Errorf("failed to send response to client: %v", err))
fmt.Errorf("failed to flush to client: %v", err))
}

return dualStream(targetConn, clientConn, clientConn)
Expand Down
Loading