Skip to content

Commit

Permalink
Better Timeout in Socks5 handshake
Browse files Browse the repository at this point in the history
  • Loading branch information
NI committed Sep 3, 2019
1 parent bf68b88 commit 11d6a58
Showing 1 changed file with 24 additions and 33 deletions.
57 changes: 24 additions & 33 deletions application/network/dial_socks5.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package network

import (
"context"
"net"
"time"

Expand All @@ -28,41 +29,30 @@ var (
emptyTime = time.Time{}
)

type socks5Conn struct {
net.Conn

initialReadDeadline time.Time
type socks5Dial struct {
net.Dialer
}

func (s *socks5Conn) SetDeadline(t time.Time) error {
s.initialReadDeadline = emptyTime

return s.Conn.SetDeadline(t)
}
func (s socks5Dial) Dial(
network, address string) (net.Conn, error) {
conn, dErr := s.Dialer.Dial(network, address)

func (s *socks5Conn) SetReadDeadline(t time.Time) error {
s.initialReadDeadline = emptyTime

return s.Conn.SetReadDeadline(t)
}

func (s *socks5Conn) SetWriteDeadline(t time.Time) error {
s.initialReadDeadline = emptyTime
if dErr == nil {
conn.SetReadDeadline(time.Now().Add(s.Dialer.Timeout))
}

return s.Conn.SetWriteDeadline(t)
return conn, dErr
}

func (s *socks5Conn) Read(b []byte) (int, error) {
if s.initialReadDeadline != emptyTime {
s.Conn.SetReadDeadline(s.initialReadDeadline)
s.initialReadDeadline = emptyTime
func (s socks5Dial) DialContext(
ctx context.Context, network, address string) (net.Conn, error) {
conn, dErr := s.Dialer.DialContext(ctx, network, address)

defer s.Conn.SetReadDeadline(emptyTime)
if dErr == nil {
conn.SetReadDeadline(time.Now().Add(s.Dialer.Timeout))
}

rLen, rErr := s.Conn.Read(b)

return rLen, rErr
return conn, dErr
}

// BuildSocks5Dial builds a Socks5 dialer
Expand All @@ -82,9 +72,11 @@ func BuildSocks5Dial(
address string,
timeout time.Duration,
) (net.Conn, error) {
dialCfg := net.Dialer{
Timeout: timeout,
Deadline: time.Now().Add(timeout),
dialCfg := socks5Dial{
Dialer: net.Dialer{
Timeout: timeout,
Deadline: time.Now().Add(timeout),
},
}

dial, dialErr := proxy.SOCKS5("tcp", socks5Address, auth, &dialCfg)
Expand All @@ -99,9 +91,8 @@ func BuildSocks5Dial(
return nil, dialErr
}

return &socks5Conn{
Conn: dialConn,
initialReadDeadline: dialCfg.Deadline,
}, nil
dialConn.SetReadDeadline(emptyTime)

return dialConn, nil
}, nil
}

0 comments on commit 11d6a58

Please sign in to comment.