2018-08-11 20:00:34 +00:00
|
|
|
package redir
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
|
2021-06-10 06:05:56 +00:00
|
|
|
"github.com/Dreamacro/clash/adapter/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 {
|
2018-11-22 03:54:01 +00:00
|
|
|
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 {
|
2018-11-22 03:54:01 +00:00
|
|
|
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 {
|
2018-11-22 03:54:01 +00:00
|
|
|
if rl.closed {
|
2018-08-11 20:00:34 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
go handleRedir(c)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2018-11-22 03:54:01 +00:00
|
|
|
return rl, nil
|
|
|
|
}
|
|
|
|
|
2018-12-05 13:13:29 +00:00
|
|
|
func (l *RedirListener) Close() {
|
2018-11-22 03:54:01 +00:00
|
|
|
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 {
|
2018-11-22 03:54:01 +00:00
|
|
|
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)
|
2020-04-24 16:39:30 +00:00
|
|
|
tunnel.Add(inbound.NewSocket(target, conn, C.REDIR))
|
2018-08-11 20:00:34 +00:00
|
|
|
}
|