Optimization: use client session cache for TLS connection (#26)

This commit is contained in:
changx
2018-11-01 11:54:45 +08:00
committed by Dreamacro
parent c5757a9b11
commit fd63707399
4 changed files with 67 additions and 19 deletions

View File

@ -32,6 +32,7 @@ type Socks5 struct {
name string
tls bool
skipCertVerify bool
tlsConfig *tls.Config
}
type Socks5Option struct {
@ -54,11 +55,9 @@ func (ss *Socks5) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err e
c, err := net.DialTimeout("tcp", ss.addr, tcpTimeout)
if err == nil && ss.tls {
tlsConfig := tls.Config{
InsecureSkipVerify: ss.skipCertVerify,
MaxVersion: tls.VersionTLS12,
}
c = tls.Client(c, &tlsConfig)
cc := tls.Client(c, ss.tlsConfig)
err = cc.Handshake()
c = cc
}
if err != nil {
@ -103,10 +102,22 @@ func (ss *Socks5) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
}
func NewSocks5(option Socks5Option) *Socks5 {
var tlsConfig *tls.Config
if option.TLS {
tlsConfig = &tls.Config{
InsecureSkipVerify: option.SkipCertVerify,
ClientSessionCache: getClientSessionCache(),
MinVersion: tls.VersionTLS11,
MaxVersion: tls.VersionTLS12,
ServerName: option.Server,
}
}
return &Socks5{
addr: fmt.Sprintf("%s:%d", option.Server, option.Port),
name: option.Name,
tls: option.TLS,
skipCertVerify: option.SkipCertVerify,
tlsConfig: tlsConfig,
}
}

View File

@ -1,10 +1,12 @@
package adapters
import (
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"sync"
"time"
C "github.com/Dreamacro/clash/constant"
@ -14,6 +16,11 @@ const (
tcpTimeout = 5 * time.Second
)
var (
globalClientSessionCache tls.ClientSessionCache
once sync.Once
)
// DelayTest get the delay for the specified URL
func DelayTest(proxy C.Proxy, url string) (t int16, err error) {
addr, err := urlToMetadata(url)
@ -95,3 +102,10 @@ func tcpKeepAlive(c net.Conn) {
tcp.SetKeepAlivePeriod(30 * time.Second)
}
}
func getClientSessionCache() tls.ClientSessionCache {
once.Do(func() {
globalClientSessionCache = tls.NewLRUClientSessionCache(128)
})
return globalClientSessionCache
}

View File

@ -72,6 +72,7 @@ func NewVmess(option VmessOption) (*Vmess, error) {
NetWork: option.Network,
WebSocketPath: option.WSPath,
SkipCertVerify: option.SkipCertVerify,
SessionCacahe: getClientSessionCache(),
})
if err != nil {
return nil, err