From 6e3326316778dbca09db481fdf9a61fb3a30bc3d Mon Sep 17 00:00:00 2001 From: gVisor bot Date: Sat, 15 Jan 2022 19:33:21 +0800 Subject: [PATCH] Fix: tls handshake requires a timeout (#1893) --- constant/adapters.go | 1 + transport/gun/gun.go | 8 +++++++- transport/trojan/trojan.go | 8 +++++++- transport/vmess/tls.go | 9 ++++++++- 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/constant/adapters.go b/constant/adapters.go index 136e48eb..dd754427 100644 --- a/constant/adapters.go +++ b/constant/adapters.go @@ -32,6 +32,7 @@ const ( const ( DefaultTCPTimeout = 5 * time.Second DefaultUDPTimeout = DefaultTCPTimeout + DefaultTLSTimeout = DefaultTCPTimeout ) type Connection interface { diff --git a/transport/gun/gun.go b/transport/gun/gun.go index f6f76116..43988004 100644 --- a/transport/gun/gun.go +++ b/transport/gun/gun.go @@ -5,6 +5,7 @@ package gun import ( "bufio" + "context" "crypto/tls" "encoding/binary" "errors" @@ -17,6 +18,7 @@ import ( "time" "github.com/Dreamacro/clash/common/pool" + C "github.com/Dreamacro/clash/constant" "go.uber.org/atomic" "golang.org/x/net/http2" @@ -173,7 +175,11 @@ func NewHTTP2Client(dialFn DialFn, tlsConfig *tls.Config) *http2.Transport { } cn := tls.Client(pconn, cfg) - if err := cn.Handshake(); err != nil { + + // fix tls handshake not timeout + ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout) + defer cancel() + if err := cn.HandshakeContext(ctx); err != nil { pconn.Close() return nil, err } diff --git a/transport/trojan/trojan.go b/transport/trojan/trojan.go index 9d9a33b9..ac9f17dd 100644 --- a/transport/trojan/trojan.go +++ b/transport/trojan/trojan.go @@ -1,6 +1,7 @@ package trojan import ( + "context" "crypto/sha256" "crypto/tls" "encoding/binary" @@ -12,6 +13,7 @@ import ( "sync" "github.com/Dreamacro/clash/common/pool" + C "github.com/Dreamacro/clash/constant" "github.com/Dreamacro/clash/transport/socks5" "github.com/Dreamacro/clash/transport/vmess" ) @@ -68,7 +70,11 @@ func (t *Trojan) StreamConn(conn net.Conn) (net.Conn, error) { } tlsConn := tls.Client(conn, tlsConfig) - if err := tlsConn.Handshake(); err != nil { + + // fix tls handshake not timeout + ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout) + defer cancel() + if err := tlsConn.HandshakeContext(ctx); err != nil { return nil, err } diff --git a/transport/vmess/tls.go b/transport/vmess/tls.go index 234c3147..e4f29a2f 100644 --- a/transport/vmess/tls.go +++ b/transport/vmess/tls.go @@ -1,8 +1,11 @@ package vmess import ( + "context" "crypto/tls" "net" + + C "github.com/Dreamacro/clash/constant" ) type TLSConfig struct { @@ -19,6 +22,10 @@ func StreamTLSConn(conn net.Conn, cfg *TLSConfig) (net.Conn, error) { } tlsConn := tls.Client(conn, tlsConfig) - err := tlsConn.Handshake() + + // fix tls handshake not timeout + ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout) + defer cancel() + err := tlsConn.HandshakeContext(ctx) return tlsConn, err }