clash/proxy/redir/tcp.go

60 lines
1,005 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-12-05 13:13:29 +00:00
C "github.com/Dreamacro/clash/constant"
2018-12-03 15:41:40 +00:00
"github.com/Dreamacro/clash/log"
2018-08-11 20:00:34 +00:00
"github.com/Dreamacro/clash/tunnel"
)
2018-12-05 13:13:29 +00:00
type RedirListener struct {
net.Listener
address string
closed bool
}
2018-12-05 13:13:29 +00:00
func NewRedirProxy(addr string) (*RedirListener, error) {
2018-08-11 20:00:34 +00:00
l, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
2018-08-11 20:00:34 +00:00
}
2018-12-05 13:13:29 +00:00
rl := &RedirListener{l, addr, false}
2018-08-11 20:00:34 +00:00
go func() {
2018-12-03 15:41:40 +00:00
log.Infoln("Redir proxy listening at: %s", addr)
2018-08-11 20:00:34 +00:00
for {
c, err := l.Accept()
if err != nil {
if rl.closed {
2018-08-11 20:00:34 +00:00
break
}
continue
}
go handleRedir(c)
}
}()
return rl, nil
}
2018-12-05 13:13:29 +00:00
func (l *RedirListener) Close() {
l.closed = true
l.Listener.Close()
}
2018-08-11 20:00:34 +00:00
2018-12-05 13:13:29 +00:00
func (l *RedirListener) Address() string {
return l.address
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)
tunnel.Add(inbound.NewSocket(target, conn, C.REDIR))
2018-08-11 20:00:34 +00:00
}