2018-06-14 01:00:58 +08:00
|
|
|
package socks
|
2018-06-10 22:50:03 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
|
2018-07-26 00:04:59 +08:00
|
|
|
"github.com/Dreamacro/clash/adapters/local"
|
2018-06-14 01:00:58 +08:00
|
|
|
C "github.com/Dreamacro/clash/constant"
|
2018-06-10 22:50:03 +08:00
|
|
|
"github.com/Dreamacro/clash/tunnel"
|
|
|
|
|
|
|
|
"github.com/riobard/go-shadowsocks2/socks"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2018-07-26 00:04:59 +08:00
|
|
|
tun = tunnel.Instance()
|
2018-06-10 22:50:03 +08:00
|
|
|
)
|
|
|
|
|
2018-07-15 22:23:20 +08:00
|
|
|
func NewSocksProxy(addr string) (*C.ProxySignal, error) {
|
|
|
|
l, err := net.Listen("tcp", addr)
|
2018-06-10 22:50:03 +08:00
|
|
|
if err != nil {
|
2018-07-15 22:23:20 +08:00
|
|
|
return nil, err
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
2018-07-15 22:23:20 +08:00
|
|
|
|
|
|
|
done := make(chan struct{})
|
|
|
|
closed := make(chan struct{})
|
|
|
|
signal := &C.ProxySignal{
|
|
|
|
Done: done,
|
|
|
|
Closed: closed,
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
2018-07-15 22:23:20 +08:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
log.Infof("SOCKS proxy listening at: %s", addr)
|
|
|
|
for {
|
|
|
|
c, err := l.Accept()
|
|
|
|
if err != nil {
|
|
|
|
if _, open := <-done; !open {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
go handleSocks(c)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
<-done
|
|
|
|
close(done)
|
|
|
|
l.Close()
|
|
|
|
closed <- struct{}{}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return signal, nil
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func handleSocks(conn net.Conn) {
|
|
|
|
target, err := socks.Handshake(conn)
|
|
|
|
if err != nil {
|
2018-06-12 09:18:15 +08:00
|
|
|
conn.Close()
|
|
|
|
return
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
|
|
|
conn.(*net.TCPConn).SetKeepAlive(true)
|
2018-07-26 00:04:59 +08:00
|
|
|
tun.Add(adapters.NewSocks(target, conn))
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|