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
|
|
|
C "github.com/Dreamacro/clash/constant"
|
|
|
|
"github.com/Dreamacro/clash/tunnel"
|
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
tun = tunnel.Instance()
|
|
|
|
)
|
|
|
|
|
|
|
|
func NewRedirProxy(addr string) (*C.ProxySignal, error) {
|
|
|
|
l, err := net.Listen("tcp", addr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
done := make(chan struct{})
|
|
|
|
closed := make(chan struct{})
|
|
|
|
signal := &C.ProxySignal{
|
|
|
|
Done: done,
|
|
|
|
Closed: closed,
|
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
log.Infof("Redir proxy listening at: %s", addr)
|
|
|
|
for {
|
|
|
|
c, err := l.Accept()
|
|
|
|
if err != nil {
|
|
|
|
if _, open := <-done; !open {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
go handleRedir(c)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
<-done
|
|
|
|
close(done)
|
|
|
|
l.Close()
|
|
|
|
closed <- struct{}{}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return signal, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
}
|