mihomo/listener/tproxy/tproxy.go

84 lines
1.6 KiB
Go
Raw Normal View History

2021-06-13 17:23:10 +08:00
package tproxy
import (
"net"
2021-06-10 14:05:56 +08:00
"github.com/Dreamacro/clash/adapter/inbound"
C "github.com/Dreamacro/clash/constant"
2021-05-13 22:18:49 +08:00
"github.com/Dreamacro/clash/transport/socks5"
)
2021-06-13 17:23:10 +08:00
type Listener struct {
2022-12-04 22:08:20 +08:00
listener net.Listener
addr string
closed bool
name string
specialRules string
}
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-04 22:08:20 +08:00
func (l *Listener) handleTProxy(name, specialRules string, conn net.Conn, in chan<- C.ConnContext) {
2021-08-01 00:35:37 +08:00
target := socks5.ParseAddrToSocksAddr(conn.LocalAddr())
conn.(*net.TCPConn).SetKeepAlive(true)
2022-12-04 22:08:20 +08:00
in <- inbound.NewSocketWithInfos(target, conn, C.TPROXY, name, specialRules)
2021-08-01 00:35:37 +08:00
}
2021-06-13 17:23:10 +08:00
func New(addr string, in chan<- C.ConnContext) (*Listener, error) {
return NewWithInfos(addr, "DEFAULT-TPROXY", "", in)
2022-12-04 13:37:14 +08:00
}
2022-12-04 22:08:20 +08:00
func NewWithInfos(addr, name, specialRules string, in chan<- C.ConnContext) (*Listener, error) {
l, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
tl := l.(*net.TCPListener)
rc, err := tl.SyscallConn()
if err != nil {
return nil, err
}
err = setsockopt(rc, addr)
if err != nil {
return nil, err
}
2021-06-13 17:23:10 +08:00
rl := &Listener{
2022-12-04 22:08:20 +08:00
listener: l,
addr: addr,
name: name,
specialRules: specialRules,
}
go func() {
for {
c, err := l.Accept()
if err != nil {
if rl.closed {
break
}
continue
}
2022-12-04 22:08:20 +08:00
go rl.handleTProxy(rl.name, rl.specialRules, c, in)
}
}()
return rl, nil
}