2018-08-12 04:00:34 +08:00
|
|
|
package redir
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
|
2018-09-30 12:25:52 +08:00
|
|
|
"github.com/Dreamacro/clash/adapters/inbound"
|
2018-08-12 04:00:34 +08:00
|
|
|
"github.com/Dreamacro/clash/tunnel"
|
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
tun = tunnel.Instance()
|
|
|
|
)
|
|
|
|
|
2018-11-22 11:54:01 +08:00
|
|
|
type redirListener struct {
|
|
|
|
net.Listener
|
|
|
|
address string
|
|
|
|
closed bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewRedirProxy(addr string) (*redirListener, error) {
|
2018-08-12 04:00:34 +08:00
|
|
|
l, err := net.Listen("tcp", addr)
|
|
|
|
if err != nil {
|
2018-11-22 11:54:01 +08:00
|
|
|
return nil, err
|
2018-08-12 04:00:34 +08:00
|
|
|
}
|
2018-11-22 11:54:01 +08:00
|
|
|
rl := &redirListener{l, addr, false}
|
2018-08-12 04:00:34 +08:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
log.Infof("Redir proxy listening at: %s", addr)
|
|
|
|
for {
|
|
|
|
c, err := l.Accept()
|
|
|
|
if err != nil {
|
2018-11-22 11:54:01 +08:00
|
|
|
if rl.closed {
|
2018-08-12 04:00:34 +08:00
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
go handleRedir(c)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2018-11-22 11:54:01 +08:00
|
|
|
return rl, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *redirListener) Close() {
|
|
|
|
l.closed = true
|
|
|
|
l.Listener.Close()
|
|
|
|
}
|
2018-08-12 04:00:34 +08:00
|
|
|
|
2018-11-22 11:54:01 +08:00
|
|
|
func (l *redirListener) Address() string {
|
|
|
|
return l.address
|
2018-08-12 04:00:34 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func handleRedir(conn net.Conn) {
|
|
|
|
target, err := parserPacket(conn)
|
|
|
|
if err != nil {
|
|
|
|
conn.Close()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
conn.(*net.TCPConn).SetKeepAlive(true)
|
2018-08-27 00:06:40 +08:00
|
|
|
tun.Add(adapters.NewSocket(target, conn))
|
2018-08-12 04:00:34 +08:00
|
|
|
}
|