2018-08-12 04:00:34 +08:00
|
|
|
package redir
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
|
2021-06-10 14:05:56 +08:00
|
|
|
"github.com/Dreamacro/clash/adapter/inbound"
|
2023-09-02 16:25:55 +08:00
|
|
|
N "github.com/Dreamacro/clash/common/net"
|
2018-12-05 21:13:29 +08:00
|
|
|
C "github.com/Dreamacro/clash/constant"
|
2018-08-12 04:00:34 +08:00
|
|
|
)
|
|
|
|
|
2021-06-13 17:23:10 +08:00
|
|
|
type Listener struct {
|
2022-12-05 00:20:50 +08:00
|
|
|
listener net.Listener
|
|
|
|
addr string
|
|
|
|
closed bool
|
2018-11-22 11:54:01 +08:00
|
|
|
}
|
|
|
|
|
2021-08-01 00:35:37 +08:00
|
|
|
// RawAddress implements C.Listener
|
|
|
|
func (l *Listener) RawAddress() string {
|
|
|
|
return l.addr
|
|
|
|
}
|
|
|
|
|
|
|
|
// Address implements C.Listener
|
|
|
|
func (l *Listener) Address() string {
|
|
|
|
return l.listener.Addr().String()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close implements C.Listener
|
|
|
|
func (l *Listener) Close() error {
|
|
|
|
l.closed = true
|
|
|
|
return l.listener.Close()
|
|
|
|
}
|
|
|
|
|
2022-12-05 00:20:50 +08:00
|
|
|
func New(addr string, in chan<- C.ConnContext, additions ...inbound.Addition) (*Listener, error) {
|
|
|
|
if len(additions) == 0 {
|
2022-12-05 10:12:53 +08:00
|
|
|
additions = []inbound.Addition{
|
|
|
|
inbound.WithInName("DEFAULT-REDIR"),
|
|
|
|
inbound.WithSpecialRules(""),
|
|
|
|
}
|
2022-12-05 00:20:50 +08:00
|
|
|
}
|
2018-08-12 04:00:34 +08:00
|
|
|
l, err := net.Listen("tcp", addr)
|
|
|
|
if err != nil {
|
2018-11-22 11:54:01 +08:00
|
|
|
return nil, err
|
2018-08-12 04:00:34 +08:00
|
|
|
}
|
2021-07-19 14:07:51 +08:00
|
|
|
rl := &Listener{
|
2022-12-05 00:20:50 +08:00
|
|
|
listener: l,
|
|
|
|
addr: addr,
|
2021-07-19 14:07:51 +08:00
|
|
|
}
|
2018-08-12 04:00:34 +08:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
c, err := l.Accept()
|
|
|
|
if err != nil {
|
2018-11-22 11:54:01 +08:00
|
|
|
if rl.closed {
|
2018-08-12 04:00:34 +08:00
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
2022-12-05 00:20:50 +08:00
|
|
|
go handleRedir(c, in, additions...)
|
2018-08-12 04:00:34 +08:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2018-11-22 11:54:01 +08:00
|
|
|
return rl, nil
|
|
|
|
}
|
2022-12-05 00:20:50 +08:00
|
|
|
func handleRedir(conn net.Conn, in chan<- C.ConnContext, additions ...inbound.Addition) {
|
2018-08-12 04:00:34 +08:00
|
|
|
target, err := parserPacket(conn)
|
|
|
|
if err != nil {
|
|
|
|
conn.Close()
|
|
|
|
return
|
|
|
|
}
|
2023-09-02 16:25:55 +08:00
|
|
|
N.TCPKeepAlive(conn)
|
2022-12-05 00:20:50 +08:00
|
|
|
in <- inbound.NewSocket(target, conn, C.REDIR, additions...)
|
2018-08-12 04:00:34 +08:00
|
|
|
}
|