Skip to content

Commit

Permalink
martian: add timeout for upstream HTTP connect
Browse files Browse the repository at this point in the history
The timeout is 60s by default.
  • Loading branch information
Choraden committed Jan 18, 2024
1 parent c7898c2 commit c81ba63
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions http_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@ func (hp *HTTPProxy) configureProxy() error {
hp.proxy.RequestIDHeader = hp.config.RequestIDHeader
hp.proxy.ConnectRequestModifier = hp.config.ConnectRequestModifier
hp.proxy.ConnectFunc = hp.config.ConnectFunc
hp.proxy.ConnectTimeout = 60 * time.Second
hp.proxy.WithoutWarning = true
hp.proxy.ErrorResponse = hp.errorResponse
hp.proxy.IdleTimeout = hp.config.IdleTimeout
Expand Down
14 changes: 13 additions & 1 deletion internal/martian/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,9 @@ type Proxy struct {
// Implementations can return ErrConnectFallback to indicate that the CONNECT request should be handled by martian.
ConnectFunc ConnectFunc

// ConnectTimeout specifies the maximum amount of time to connect to upstream before cancelling request.
ConnectTimeout time.Duration

// MITMFilter specifies a function to determine whether a CONNECT request should be MITMed.
MITMFilter func(*http.Request) bool

Expand Down Expand Up @@ -965,7 +968,16 @@ func (p *Proxy) connectHTTP(req *http.Request, proxyURL *url.URL) (res *http.Res
d = dialvia.HTTPProxy(p.dial, proxyURL)
}
d.ConnectRequestModifier = p.ConnectRequestModifier
res, conn, err = d.DialContextR(req.Context(), "tcp", req.URL.Host)

var ctx context.Context
if p.ConnectTimeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(req.Context(), p.ConnectTimeout)
defer cancel()
} else {
ctx = req.Context()
}
res, conn, err = d.DialContextR(ctx, "tcp", req.URL.Host)

if res != nil {
if res.StatusCode/100 == 2 {
Expand Down

0 comments on commit c81ba63

Please sign in to comment.