2021-06-13 09:23:10 +00:00
|
|
|
package tproxy
|
2020-11-09 02:46:10 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
|
2021-06-10 06:05:56 +00:00
|
|
|
"github.com/Dreamacro/clash/adapter/inbound"
|
2020-11-09 02:46:10 +00:00
|
|
|
C "github.com/Dreamacro/clash/constant"
|
2021-05-13 14:18:49 +00:00
|
|
|
"github.com/Dreamacro/clash/transport/socks5"
|
2020-11-09 02:46:10 +00:00
|
|
|
)
|
|
|
|
|
2021-06-13 09:23:10 +00:00
|
|
|
type Listener struct {
|
2021-06-13 15:05:22 +00:00
|
|
|
listener net.Listener
|
2021-07-31 16:35:37 +00:00
|
|
|
addr string
|
2021-06-13 15:05:22 +00:00
|
|
|
closed bool
|
2020-11-09 02:46:10 +00:00
|
|
|
}
|
|
|
|
|
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 (l *Listener) handleTProxy(conn net.Conn, in chan<- C.ConnContext) {
|
|
|
|
target := socks5.ParseAddrToSocksAddr(conn.LocalAddr())
|
|
|
|
conn.(*net.TCPConn).SetKeepAlive(true)
|
|
|
|
in <- inbound.NewSocket(target, conn, C.TPROXY)
|
|
|
|
}
|
|
|
|
|
2021-06-13 09:23:10 +00:00
|
|
|
func New(addr string, in chan<- C.ConnContext) (*Listener, error) {
|
2020-11-09 02:46:10 +00: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 09:23:10 +00:00
|
|
|
rl := &Listener{
|
2021-06-13 15:05:22 +00:00
|
|
|
listener: l,
|
2021-07-31 16:35:37 +00:00
|
|
|
addr: addr,
|
2020-11-09 02:46:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
c, err := l.Accept()
|
|
|
|
if err != nil {
|
|
|
|
if rl.closed {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
2021-06-13 09:23:10 +00:00
|
|
|
go rl.handleTProxy(c, in)
|
2020-11-09 02:46:10 +00:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return rl, nil
|
|
|
|
}
|