2021-06-13 17:23:10 +08:00
|
|
|
package tproxy
|
2020-11-09 10:46:10 +08:00
|
|
|
|
|
|
|
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"
|
2020-11-09 10:46:10 +08:00
|
|
|
C "github.com/Dreamacro/clash/constant"
|
2021-05-13 22:18:49 +08:00
|
|
|
"github.com/Dreamacro/clash/transport/socks5"
|
2020-11-09 10:46:10 +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
|
2020-11-09 10:46:10 +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()
|
|
|
|
}
|
|
|
|
|
2023-09-28 18:59:31 +08:00
|
|
|
func (l *Listener) handleTProxy(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
|
2021-08-01 00:35:37 +08:00
|
|
|
target := socks5.ParseAddrToSocksAddr(conn.LocalAddr())
|
2023-09-02 16:25:55 +08:00
|
|
|
N.TCPKeepAlive(conn)
|
2023-09-28 18:59:31 +08:00
|
|
|
tunnel.HandleTCPConn(inbound.NewSocket(target, conn, C.TPROXY, additions...))
|
2021-08-01 00:35:37 +08:00
|
|
|
}
|
|
|
|
|
2023-09-28 18:59:31 +08:00
|
|
|
func New(addr string, tunnel C.Tunnel, additions ...inbound.Addition) (*Listener, error) {
|
2022-12-05 00:20:50 +08:00
|
|
|
if len(additions) == 0 {
|
2022-12-05 10:12:53 +08:00
|
|
|
additions = []inbound.Addition{
|
|
|
|
inbound.WithInName("DEFAULT-TPROXY"),
|
|
|
|
inbound.WithSpecialRules(""),
|
|
|
|
}
|
2022-12-05 00:20:50 +08:00
|
|
|
}
|
2020-11-09 10:46:10 +08:00
|
|
|
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-05 00:20:50 +08:00
|
|
|
listener: l,
|
|
|
|
addr: addr,
|
2020-11-09 10:46:10 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
c, err := l.Accept()
|
|
|
|
if err != nil {
|
|
|
|
if rl.closed {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
2023-09-28 18:59:31 +08:00
|
|
|
go rl.handleTProxy(c, tunnel, additions...)
|
2020-11-09 10:46:10 +08:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return rl, nil
|
|
|
|
}
|