Clash.Meta/listener/redir/tcp.go

57 lines
895 B
Go
Raw Normal View History

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"
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 {
net.Listener
address string
closed bool
}
2021-06-13 17:23:10 +08:00
func New(addr string, in chan<- C.ConnContext) (*Listener, 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
}
2021-06-13 17:23:10 +08:00
rl := &Listener{l, addr, false}
2018-08-12 04:00:34 +08:00
go func() {
for {
c, err := l.Accept()
if err != nil {
if rl.closed {
2018-08-12 04:00:34 +08:00
break
}
continue
}
2021-06-13 17:23:10 +08:00
go handleRedir(c, in)
2018-08-12 04:00:34 +08:00
}
}()
return rl, nil
}
2021-06-13 17:23:10 +08:00
func (l *Listener) Close() {
l.closed = true
l.Listener.Close()
}
2018-08-12 04:00:34 +08:00
2021-06-13 17:23:10 +08:00
func (l *Listener) Address() string {
return l.address
2018-08-12 04:00:34 +08:00
}
2021-06-13 17:23:10 +08:00
func handleRedir(conn net.Conn, in chan<- C.ConnContext) {
2018-08-12 04:00:34 +08:00
target, err := parserPacket(conn)
if err != nil {
conn.Close()
return
}
conn.(*net.TCPConn).SetKeepAlive(true)
2021-06-13 17:23:10 +08:00
in <- inbound.NewSocket(target, conn, C.REDIR)
2018-08-12 04:00:34 +08:00
}