clash/proxy/socks/tcp.go

69 lines
1.2 KiB
Go
Raw Normal View History

2018-06-13 17:00:58 +00:00
package socks
2018-06-10 14:50:03 +00:00
import (
"net"
2019-04-23 15:29:36 +00:00
adapters "github.com/Dreamacro/clash/adapters/inbound"
2019-04-25 05:48:47 +00:00
"github.com/Dreamacro/clash/component/socks5"
2018-12-05 13:13:29 +00:00
C "github.com/Dreamacro/clash/constant"
2018-12-03 15:41:40 +00:00
"github.com/Dreamacro/clash/log"
2018-06-10 14:50:03 +00:00
"github.com/Dreamacro/clash/tunnel"
)
var (
tun = tunnel.Instance()
2018-06-10 14:50:03 +00:00
)
2018-12-05 13:13:29 +00:00
type SockListener struct {
net.Listener
address string
closed bool
}
2018-12-05 13:13:29 +00:00
func NewSocksProxy(addr string) (*SockListener, error) {
2018-07-15 14:23:20 +00:00
l, err := net.Listen("tcp", addr)
2018-06-10 14:50:03 +00:00
if err != nil {
return nil, err
2018-06-10 14:50:03 +00:00
}
2018-07-15 14:23:20 +00:00
2018-12-05 13:13:29 +00:00
sl := &SockListener{l, addr, false}
2018-07-15 14:23:20 +00:00
go func() {
2018-12-03 15:41:40 +00:00
log.Infoln("SOCKS proxy listening at: %s", addr)
2018-07-15 14:23:20 +00:00
for {
c, err := l.Accept()
if err != nil {
if sl.closed {
2018-07-15 14:23:20 +00:00
break
}
continue
}
go handleSocks(c)
}
}()
return sl, nil
}
2018-12-05 13:13:29 +00:00
func (l *SockListener) Close() {
l.closed = true
l.Listener.Close()
}
2018-07-15 14:23:20 +00:00
2018-12-05 13:13:29 +00:00
func (l *SockListener) Address() string {
return l.address
2018-06-10 14:50:03 +00:00
}
func handleSocks(conn net.Conn) {
2019-04-25 05:48:47 +00:00
target, command, err := socks5.ServerHandshake(conn)
2018-06-10 14:50:03 +00:00
if err != nil {
conn.Close()
return
2018-06-10 14:50:03 +00:00
}
conn.(*net.TCPConn).SetKeepAlive(true)
2019-04-25 05:48:47 +00:00
if command == socks5.CmdUDPAssociate {
2019-04-23 15:29:36 +00:00
tun.Add(adapters.NewSocket(target, conn, C.SOCKS, C.UDP))
return
}
tun.Add(adapters.NewSocket(target, conn, C.SOCKS, C.TCP))
}