clash/proxy/redir/tcp.go

57 lines
908 B
Go
Raw Normal View History

2018-08-11 20:00:34 +00:00
package redir
import (
"net"
2018-09-30 04:25:52 +00:00
"github.com/Dreamacro/clash/adapters/inbound"
2018-08-11 20:00:34 +00:00
"github.com/Dreamacro/clash/tunnel"
log "github.com/sirupsen/logrus"
)
var (
tun = tunnel.Instance()
)
2018-11-21 05:47:46 +00:00
func NewRedirProxy(addr string) (chan<- struct{}, <-chan struct{}, error) {
2018-08-11 20:00:34 +00:00
l, err := net.Listen("tcp", addr)
if err != nil {
2018-11-21 05:47:46 +00:00
return nil, nil, err
2018-08-11 20:00:34 +00:00
}
done := make(chan struct{})
closed := make(chan struct{})
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
l.Close()
closed <- struct{}{}
}()
2018-11-21 05:47:46 +00:00
return done, closed, nil
2018-08-11 20:00:34 +00:00
}
func handleRedir(conn net.Conn) {
target, err := parserPacket(conn)
if err != nil {
conn.Close()
return
}
conn.(*net.TCPConn).SetKeepAlive(true)
2018-08-26 16:06:40 +00:00
tun.Add(adapters.NewSocket(target, conn))
2018-08-11 20:00:34 +00:00
}