clash/listener/redir/tcp.go

74 lines
1.3 KiB
Go
Raw Normal View History

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"
N "github.com/Dreamacro/clash/common/net"
2018-12-05 13:13:29 +00:00
C "github.com/Dreamacro/clash/constant"
2018-08-11 20:00:34 +00:00
)
2021-06-13 09:23:10 +00:00
type Listener struct {
listener net.Listener
addr string
closed bool
}
2021-07-31 16:35:37 +00: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()
}
func New(addr string, tunnel C.Tunnel, additions ...inbound.Addition) (*Listener, error) {
if len(additions) == 0 {
additions = []inbound.Addition{
inbound.WithInName("DEFAULT-REDIR"),
inbound.WithSpecialRules(""),
}
}
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
}
rl := &Listener{
listener: l,
addr: addr,
}
2018-08-11 20:00:34 +00:00
go func() {
for {
c, err := l.Accept()
if err != nil {
if rl.closed {
2018-08-11 20:00:34 +00:00
break
}
continue
}
go handleRedir(c, tunnel, additions...)
2018-08-11 20:00:34 +00:00
}
}()
return rl, nil
}
func handleRedir(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
2018-08-11 20:00:34 +00:00
target, err := parserPacket(conn)
if err != nil {
conn.Close()
return
}
N.TCPKeepAlive(conn)
tunnel.HandleTCPConn(inbound.NewSocket(target, conn, C.REDIR, additions...))
2018-08-11 20:00:34 +00:00
}