2018-06-14 01:00:58 +08:00
|
|
|
package socks
|
2018-06-10 22:50:03 +08:00
|
|
|
|
|
|
|
import (
|
2019-07-25 17:47:39 +08:00
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
2018-06-10 22:50:03 +08:00
|
|
|
"net"
|
|
|
|
|
2019-04-23 23:29:36 +08:00
|
|
|
adapters "github.com/Dreamacro/clash/adapters/inbound"
|
2019-04-25 13:48:47 +08:00
|
|
|
"github.com/Dreamacro/clash/component/socks5"
|
2018-12-05 21:13:29 +08:00
|
|
|
C "github.com/Dreamacro/clash/constant"
|
2018-12-03 23:41:40 +08:00
|
|
|
"github.com/Dreamacro/clash/log"
|
2019-06-27 17:04:25 +08:00
|
|
|
authStore "github.com/Dreamacro/clash/proxy/auth"
|
2018-06-10 22:50:03 +08:00
|
|
|
"github.com/Dreamacro/clash/tunnel"
|
|
|
|
)
|
|
|
|
|
2018-12-05 21:13:29 +08:00
|
|
|
type SockListener struct {
|
2018-11-22 11:54:01 +08:00
|
|
|
net.Listener
|
|
|
|
address string
|
|
|
|
closed bool
|
|
|
|
}
|
|
|
|
|
2018-12-05 21:13:29 +08:00
|
|
|
func NewSocksProxy(addr string) (*SockListener, error) {
|
2018-07-15 22:23:20 +08:00
|
|
|
l, err := net.Listen("tcp", addr)
|
2018-06-10 22:50:03 +08:00
|
|
|
if err != nil {
|
2018-11-22 11:54:01 +08:00
|
|
|
return nil, err
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
2018-07-15 22:23:20 +08:00
|
|
|
|
2018-12-05 21:13:29 +08:00
|
|
|
sl := &SockListener{l, addr, false}
|
2018-07-15 22:23:20 +08:00
|
|
|
go func() {
|
2018-12-03 23:41:40 +08:00
|
|
|
log.Infoln("SOCKS proxy listening at: %s", addr)
|
2018-07-15 22:23:20 +08:00
|
|
|
for {
|
|
|
|
c, err := l.Accept()
|
|
|
|
if err != nil {
|
2018-11-22 11:54:01 +08:00
|
|
|
if sl.closed {
|
2018-07-15 22:23:20 +08:00
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
2020-05-12 11:29:53 +08:00
|
|
|
go HandleSocks(c)
|
2018-07-15 22:23:20 +08:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2018-11-22 11:54:01 +08:00
|
|
|
return sl, nil
|
|
|
|
}
|
|
|
|
|
2018-12-05 21:13:29 +08:00
|
|
|
func (l *SockListener) Close() {
|
2018-11-22 11:54:01 +08:00
|
|
|
l.closed = true
|
|
|
|
l.Listener.Close()
|
|
|
|
}
|
2018-07-15 22:23:20 +08:00
|
|
|
|
2018-12-05 21:13:29 +08:00
|
|
|
func (l *SockListener) Address() string {
|
2018-11-22 11:54:01 +08:00
|
|
|
return l.address
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
|
|
|
|
2020-05-12 11:29:53 +08:00
|
|
|
func HandleSocks(conn net.Conn) {
|
2019-06-27 17:04:25 +08:00
|
|
|
target, command, err := socks5.ServerHandshake(conn, authStore.Authenticator())
|
2018-06-10 22:50:03 +08:00
|
|
|
if err != nil {
|
2018-06-12 09:18:15 +08:00
|
|
|
conn.Close()
|
|
|
|
return
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
2020-05-12 11:29:53 +08:00
|
|
|
if c, ok := conn.(*net.TCPConn); ok {
|
|
|
|
c.SetKeepAlive(true)
|
|
|
|
}
|
2019-04-25 13:48:47 +08:00
|
|
|
if command == socks5.CmdUDPAssociate {
|
2019-07-25 17:47:39 +08:00
|
|
|
defer conn.Close()
|
|
|
|
io.Copy(ioutil.Discard, conn)
|
2019-04-23 23:29:36 +08:00
|
|
|
return
|
|
|
|
}
|
2020-04-25 00:39:30 +08:00
|
|
|
tunnel.Add(adapters.NewSocket(target, conn, C.SOCKS))
|
2019-04-23 23:29:36 +08:00
|
|
|
}
|