2018-06-13 17:00:58 +00:00
|
|
|
package socks
|
2018-06-10 14:50:03 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
|
2018-09-30 04:25:52 +00:00
|
|
|
"github.com/Dreamacro/clash/adapters/inbound"
|
2018-06-10 14:50:03 +00:00
|
|
|
"github.com/Dreamacro/clash/tunnel"
|
|
|
|
|
2018-09-21 07:27:51 +00:00
|
|
|
"github.com/Dreamacro/go-shadowsocks2/socks"
|
2018-06-10 14:50:03 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2018-07-25 16:04:59 +00:00
|
|
|
tun = tunnel.Instance()
|
2018-06-10 14:50:03 +00:00
|
|
|
)
|
|
|
|
|
2018-11-22 03:54:01 +00:00
|
|
|
type sockListener struct {
|
|
|
|
net.Listener
|
|
|
|
address string
|
|
|
|
closed bool
|
|
|
|
}
|
|
|
|
|
|
|
|
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 {
|
2018-11-22 03:54:01 +00:00
|
|
|
return nil, err
|
2018-06-10 14:50:03 +00:00
|
|
|
}
|
2018-07-15 14:23:20 +00:00
|
|
|
|
2018-11-22 03:54:01 +00:00
|
|
|
sl := &sockListener{l, addr, false}
|
2018-07-15 14:23:20 +00:00
|
|
|
go func() {
|
|
|
|
log.Infof("SOCKS proxy listening at: %s", addr)
|
|
|
|
for {
|
|
|
|
c, err := l.Accept()
|
|
|
|
if err != nil {
|
2018-11-22 03:54:01 +00:00
|
|
|
if sl.closed {
|
2018-07-15 14:23:20 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
go handleSocks(c)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2018-11-22 03:54:01 +00:00
|
|
|
return sl, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *sockListener) Close() {
|
|
|
|
l.closed = true
|
|
|
|
l.Listener.Close()
|
|
|
|
}
|
2018-07-15 14:23:20 +00:00
|
|
|
|
2018-11-22 03:54:01 +00:00
|
|
|
func (l *sockListener) Address() string {
|
|
|
|
return l.address
|
2018-06-10 14:50:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func handleSocks(conn net.Conn) {
|
|
|
|
target, err := socks.Handshake(conn)
|
|
|
|
if err != nil {
|
2018-06-12 01:18:15 +00:00
|
|
|
conn.Close()
|
|
|
|
return
|
2018-06-10 14:50:03 +00:00
|
|
|
}
|
|
|
|
conn.(*net.TCPConn).SetKeepAlive(true)
|
2018-08-26 16:06:40 +00:00
|
|
|
tun.Add(adapters.NewSocket(target, conn))
|
2018-06-10 14:50:03 +00:00
|
|
|
}
|