implement timeout for CONNECT method

This commit is contained in:
Vladislav Yarmak 2020-05-19 23:13:51 +03:00
parent b346f83186
commit 902ebe89ac
2 changed files with 9 additions and 3 deletions

View File

@ -4,25 +4,31 @@ import (
"io" "io"
"net" "net"
"fmt" "fmt"
"time"
"net/http" "net/http"
"strings" "strings"
"context"
) )
type ProxyHandler struct { type ProxyHandler struct {
timeout time.Duration
logger *CondLogger logger *CondLogger
httptransport http.RoundTripper httptransport http.RoundTripper
} }
func NewProxyHandler(logger *CondLogger) *ProxyHandler { func NewProxyHandler(timeout time.Duration, logger *CondLogger) *ProxyHandler {
httptransport := &http.Transport{} httptransport := &http.Transport{}
return &ProxyHandler{ return &ProxyHandler{
timeout: timeout,
logger: logger, logger: logger,
httptransport: httptransport, httptransport: httptransport,
} }
} }
func (s *ProxyHandler) HandleTunnel(wr http.ResponseWriter, req *http.Request) { func (s *ProxyHandler) HandleTunnel(wr http.ResponseWriter, req *http.Request) {
conn, err := net.Dial("tcp", req.RequestURI) ctx, _ := context.WithTimeout(req.Context(), s.timeout)
dialer := net.Dialer{}
conn, err := dialer.DialContext(ctx, "tcp", req.RequestURI)
if err != nil { if err != nil {
s.logger.Error("Can't satisfy CONNECT request: %v", err) s.logger.Error("Can't satisfy CONNECT request: %v", err)
http.Error(wr, "Can't satisfy CONNECT request", http.StatusBadGateway) http.Error(wr, "Can't satisfy CONNECT request", http.StatusBadGateway)

View File

@ -51,7 +51,7 @@ func run() int {
log.LstdFlags | log.Lshortfile), log.LstdFlags | log.Lshortfile),
args.verbosity) args.verbosity)
mainLogger.Info("Starting proxy server...") mainLogger.Info("Starting proxy server...")
handler := NewProxyHandler(proxyLogger) handler := NewProxyHandler(args.timeout, proxyLogger)
err := http.ListenAndServe(args.bind_address, handler) err := http.ListenAndServe(args.bind_address, handler)
mainLogger.Critical("Server terminated with a reason: %v", err) mainLogger.Critical("Server terminated with a reason: %v", err)
mainLogger.Info("Shutting down...") mainLogger.Info("Shutting down...")