Skip to content

Commit

Permalink
Better handling TCP handshake for UDPAssociate
Browse files Browse the repository at this point in the history
  • Loading branch information
lixin9311 committed Nov 12, 2017
1 parent 8219d91 commit 53350ee
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
6 changes: 5 additions & 1 deletion socks/socks.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const (
ErrTTLExpired = Error(6)
ErrCommandNotSupported = Error(7)
ErrAddressNotSupported = Error(8)
InfoUDPAssociate = Error(9)
)

// MaxAddrLen is the maximum size of SOCKS address in bytes.
Expand Down Expand Up @@ -191,7 +192,6 @@ func Handshake(rw io.ReadWriter) (Addr, error) {
if err != nil {
return nil, err
}
// TODO: when disconnected, release the natmap
switch buf[1] {
case CmdConnect:
_, err = rw.Write([]byte{5, 0, 0, 1, 0, 0, 0, 0, 0, 0}) // SOCKS v5, reply succeeded
Expand All @@ -201,6 +201,10 @@ func Handshake(rw io.ReadWriter) (Addr, error) {
}
listenAddr := ParseAddr(rw.(net.Conn).LocalAddr().String())
_, err = rw.Write(append([]byte{5, 0, 0}, listenAddr...)) // SOCKS v5, reply succeeded
if err != nil {
return nil, ErrCommandNotSupported
}
err = InfoUDPAssociate
default:
return nil, ErrCommandNotSupported
}
Expand Down
16 changes: 15 additions & 1 deletion tcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,23 @@ func tcpLocal(addr, server string, shadow func(net.Conn) net.Conn, getAddr func(
go func() {
defer c.Close()
c.(*net.TCPConn).SetKeepAlive(true)
// TODO: keep the connection until disconnect then free the UDP socket
tgt, err := getAddr(c)
if err != nil {

// UDP: keep the connection until disconnect then free the UDP socket
if err == socks.InfoUDPAssociate {
buf := []byte{}
// block here
for {
_, err := c.Read(buf)
if err, ok := err.(net.Error); ok && err.Timeout() {
continue
}
logf("UDP Associate End.")
return
}
}

logf("failed to get target address: %v", err)
return
}
Expand Down

0 comments on commit 53350ee

Please sign in to comment.