Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added connection keeping feature. #291

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 126 additions & 0 deletions cycletls/client2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package cycletls

import (
"context"
http "github.com/Danny-Dasilva/fhttp"
"github.com/Danny-Dasilva/fhttp/http2"
utls "github.com/refraction-networking/utls"
"golang.org/x/net/proxy"
"net"
"time"
)

type HttpClientBuilder struct {
Browser *Browser
ProxyUrl string
ClientHelloId *utls.ClientHelloID

MaxIdleConnections int
MaxConnectionPerHost int
Timeout time.Duration

connectDialer proxy.ContextDialer

Product *http.Client
Err error
}

func (b *HttpClientBuilder) SetProxyUrl(proxyUrl string) *HttpClientBuilder {
return b
}

func (b *HttpClientBuilder) Build() (*http.Client, error) {
if b.MaxConnectionPerHost <= 0 {
b.MaxConnectionPerHost = 1
}

if b.MaxIdleConnections < 0 {
b.MaxIdleConnections = 0
}

b.buildContextDialer()

tlsDialer := newRoundTripper(*b.Browser, b.connectDialer).(*roundTripper)
tlsDialer.ClientHelloId = b.ClientHelloId

httpTransport := &http.Transport{

MaxIdleConns: b.MaxIdleConnections,
MaxConnsPerHost: b.MaxConnectionPerHost,

DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return tlsDialer.DoDialTlsContext(ctx, network, addr)
},

PostProcessPersistConn: func(persistConn *http.PersistConn) (*http.PersistConn, error) {
uConn, ok := persistConn.GetConn().(*utls.UConn)
if !ok {
return persistConn, nil
}

if uConn.ConnectionState().NegotiatedProtocol != http2.NextProtoTLS {
return persistConn, nil
}

// TODO: log.DEBUG, I don't know the equivalency of go
ua := parseUserAgent(b.Browser.UserAgent)
h2Transport := &http2.Transport{
DialTLS: func(network, addr string, cfg *utls.Config) (net.Conn, error) {
return persistConn.GetConn(), nil
},
Navigator: ua.UserAgent,
}
persistConn.SetAlt(h2Transport)

return persistConn, nil
},
}

realTransport := &customizingRequestTransport{
Browser: b.Browser,
Delegate: httpTransport,
}

return &http.Client{
Transport: realTransport,
Timeout: b.Timeout,
}, nil

}

func (b *HttpClientBuilder) buildContextDialer() {
if b.Err != nil {
return
}

if len(b.ProxyUrl) == 0 {
b.connectDialer = proxy.Direct
return
}

dialer, err := newConnectDialer(b.ProxyUrl, b.Browser.UserAgent)
if err != nil {
b.Err = err
}

b.connectDialer = dialer
}

type customizingRequestTransport struct {
Browser *Browser
Delegate http.RoundTripper
}

func (t *customizingRequestTransport) RoundTrip(req *http.Request) (*http.Response, error) {
const UserAgentHeader = "User-Agent"
if req.Header == nil {
req.Header = make(http.Header)
}

userAgents, ok := req.Header[UserAgentHeader]
if !ok || len(userAgents) == 0 {
req.Header[UserAgentHeader] = []string{t.Browser.UserAgent}
}

return t.Delegate.RoundTrip(req)
}
152 changes: 117 additions & 35 deletions cycletls/roundtripper.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"net"

"strings"
"sync"

Expand All @@ -20,8 +19,9 @@ var errProtocolNegotiated = errors.New("protocol negotiated")
type roundTripper struct {
sync.Mutex
// fix typing
JA3 string
UserAgent string
JA3 string
UserAgent string
ClientHelloId *utls.ClientHelloID

InsecureSkipVerify bool
Cookies []Cookie
Expand Down Expand Up @@ -91,42 +91,13 @@ func (rt *roundTripper) dialTLS(ctx context.Context, network, addr string) (net.
if conn := rt.cachedConnections[addr]; conn != nil {
return conn, nil
}
rawConn, err := rt.dialer.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}

var host string
if host, _, err = net.SplitHostPort(addr); err != nil {
host = addr
}
//////////////////

spec, err := StringToSpec(rt.JA3, rt.UserAgent, rt.forceHTTP1)
conn, err := rt.DoDialTlsContext(ctx, network, addr)
if err != nil {
return nil, err
}

conn := utls.UClient(rawConn, &utls.Config{ServerName: host, OmitEmptyPsk: true, InsecureSkipVerify: rt.InsecureSkipVerify}, // MinVersion: tls.VersionTLS10,
// MaxVersion: tls.VersionTLS13,

utls.HelloCustom)

if err := conn.ApplyPreset(spec); err != nil {
return nil, err
}

if err = conn.Handshake(); err != nil {
_ = conn.Close()

if err.Error() == "tls: CurvePreferences includes unsupported curve" {
//fix this
return nil, fmt.Errorf("conn.Handshake() error for tls 1.3 (please retry request): %+v", err)
}
return nil, fmt.Errorf("uTlsConn.Handshake() error: %+v", err)
}

if rt.cachedTransports[addr] != nil {
if rt.cachedTransports[addr] != nil { // Why this code here, since you already do dial tls ?
return conn, nil
}

Expand All @@ -135,7 +106,6 @@ func (rt *roundTripper) dialTLS(ctx context.Context, network, addr string) (net.
switch conn.ConnectionState().NegotiatedProtocol {
case http2.NextProtoTLS:
parsedUserAgent := parseUserAgent(rt.UserAgent)

t2 := http2.Transport{
DialTLS: rt.dialTLSHTTP2,
PushHandler: &http2.DefaultPushHandler{},
Expand All @@ -155,6 +125,38 @@ func (rt *roundTripper) dialTLS(ctx context.Context, network, addr string) (net.
return nil, errProtocolNegotiated
}

func (rt *roundTripper) DoDialTlsContext(ctx context.Context, network, addr string) (conn *utls.UConn, err error) {

var host string
if host, _, err = net.SplitHostPort(addr); err != nil {
host = addr
}

rawConn, err := rt.dialer.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}

var spec *utls.ClientHelloSpec
if len(rt.JA3) > 0 {
spec, err = StringToSpec(rt.JA3, rt.UserAgent, rt.forceHTTP1)
if err != nil {
return nil, err
}
}
Comment on lines +142 to +146
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should maybe raise an error if the JA3 isn't passed in or default it, otherwise it doesn't make a lot of sense to have the if len(rt.JA3) > 0 { check


builder := &tlsConnectionBuilder{
rawConn: rawConn,
clientHelloSpec: spec,
clientHelloId: rt.ClientHelloId,
host: host,
insecureSkipVerify: rt.InsecureSkipVerify,
}
builder.buildTlsConnection()

return builder.tlsConn, builder.err
}

func (rt *roundTripper) dialTLSHTTP2(network, addr string, _ *utls.Config) (net.Conn, error) {
return rt.dialTLS(context.Background(), network, addr)
}
Expand Down Expand Up @@ -200,3 +202,83 @@ func newRoundTripper(browser Browser, dialer ...proxy.ContextDialer) http.RoundT
forceHTTP1: browser.forceHTTP1,
}
}

type tlsConnectionBuilder struct {
rawConn net.Conn

clientHelloSpec *utls.ClientHelloSpec
clientHelloId *utls.ClientHelloID

host string
insecureSkipVerify bool

tlsConn *utls.UConn
err error
}

func (p *tlsConnectionBuilder) buildTlsConnection() {

if p.clientHelloSpec == nil && p.clientHelloId == nil {
p.err = errors.New("either clientHelloSpec or clientHelloId should be specified")
}

if p.clientHelloSpec != nil {
p.establishWithClientHelloSpec()
} else {
p.establishWithClientHelloId()
}

Comment on lines +225 to +230
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sequencing looks good

p.performHandshake()
}

func (p *tlsConnectionBuilder) establishWithClientHelloId() {

if p.err != nil {
return
}

p.tlsConn = utls.UClient(p.rawConn,
&utls.Config{ServerName: p.host, InsecureSkipVerify: p.insecureSkipVerify}, // MinVersion: tls.VersionTLS10,
// MaxVersion: tls.VersionTLS13,
*p.clientHelloId)

}

func (p *tlsConnectionBuilder) establishWithClientHelloSpec() {
if p.err != nil {
return
}

tlsConn := utls.UClient(p.rawConn,
&utls.Config{ServerName: p.host, InsecureSkipVerify: p.insecureSkipVerify}, // MinVersion: tls.VersionTLS10,
// MaxVersion: tls.VersionTLS13,
utls.HelloCustom)

if err := tlsConn.ApplyPreset(p.clientHelloSpec); err != nil {
_ = tlsConn.Close()
p.err = err
return
}

p.tlsConn = tlsConn

}

func (p *tlsConnectionBuilder) performHandshake() {
if p.err != nil {
return
}

if err := p.tlsConn.Handshake(); err != nil {
_ = p.tlsConn.Close()
p.tlsConn = nil

if err.Error() == "tls: CurvePreferences includes unsupported curve" {
//fix this
p.err = fmt.Errorf("conn.Handshake() error for tls 1.3 (please retry request): %+v", err)
}

p.err = fmt.Errorf("uTlsConn.Handshake() error: %+v", err)
}

}
Loading
Loading