clash/proxy/redir/tcp.go

60 lines
1005 B
Go
Raw Normal View History

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