From 72339a35096c226f908297403d2514ef4dad0064 Mon Sep 17 00:00:00 2001
From: Darien Raymond <admin@v2ray.com>
Date: Tue, 1 Nov 2016 00:41:46 +0100
Subject: [PATCH] fix TCP conn reuse with tls

---
 transport/internet/tcp/dialer.go | 26 +++++++++++++-------------
 transport/internet/tcp/hub.go    |  6 +++---
 2 files changed, 16 insertions(+), 16 deletions(-)

diff --git a/transport/internet/tcp/dialer.go b/transport/internet/tcp/dialer.go
index 29cd7e89..0f772b3c 100644
--- a/transport/internet/tcp/dialer.go
+++ b/transport/internet/tcp/dialer.go
@@ -36,20 +36,20 @@ func Dial(src v2net.Address, dest v2net.Destination, options internet.DialerOpti
 		if err != nil {
 			return nil, err
 		}
-	}
-	if options.Stream != nil && options.Stream.HasSecuritySettings() {
-		securitySettings, err := options.Stream.GetEffectiveSecuritySettings()
-		if err != nil {
-			log.Error("TCP: Failed to get security settings: ", err)
-			return nil, err
-		}
-		tlsConfig, ok := securitySettings.(*v2tls.Config)
-		if ok {
-			config := tlsConfig.GetTLSConfig()
-			if dest.Address.Family().IsDomain() {
-				config.ServerName = dest.Address.Domain()
+		if options.Stream != nil && options.Stream.HasSecuritySettings() {
+			securitySettings, err := options.Stream.GetEffectiveSecuritySettings()
+			if err != nil {
+				log.Error("TCP: Failed to get security settings: ", err)
+				return nil, err
+			}
+			tlsConfig, ok := securitySettings.(*v2tls.Config)
+			if ok {
+				config := tlsConfig.GetTLSConfig()
+				if dest.Address.Family().IsDomain() {
+					config.ServerName = dest.Address.Domain()
+				}
+				conn = tls.Client(conn, config)
 			}
-			conn = tls.Client(conn, config)
 		}
 	}
 	return NewConnection(id, conn, globalCache, tcpSettings), nil
diff --git a/transport/internet/tcp/hub.go b/transport/internet/tcp/hub.go
index 6c6e5f41..3b5844d3 100644
--- a/transport/internet/tcp/hub.go
+++ b/transport/internet/tcp/hub.go
@@ -77,9 +77,6 @@ func (this *TCPListener) Accept() (internet.Connection, error) {
 				return nil, connErr.err
 			}
 			conn := connErr.conn
-			if this.tlsConfig != nil {
-				conn = tls.Server(conn, this.tlsConfig)
-			}
 			return NewConnection("", conn, this, this.config), nil
 		case <-time.After(time.Second * 2):
 		}
@@ -95,6 +92,9 @@ func (this *TCPListener) KeepAccepting() {
 			this.Unlock()
 			break
 		}
+		if this.tlsConfig != nil {
+			conn = tls.Server(conn, this.tlsConfig)
+		}
 		select {
 		case this.awaitingConns <- &ConnectionWithError{
 			conn: conn,