Clash.Meta/listener/tproxy/tproxy.go

69 lines
1.1 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 {
listener net.Listener
address string
closed bool
}
2021-06-13 17:23:10 +08:00
func New(addr 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{
listener: l,
address: addr,
}
go func() {
for {
c, err := l.Accept()
if err != nil {
if rl.closed {
break
}
continue
}
2021-06-13 17:23:10 +08:00
go rl.handleTProxy(c, in)
}
}()
return rl, nil
}
2021-06-13 17:23:10 +08:00
func (l *Listener) Close() {
l.closed = true
l.listener.Close()
}
2021-06-13 17:23:10 +08:00
func (l *Listener) Address() string {
return l.address
}
2021-06-13 17:23:10 +08:00
func (l *Listener) handleTProxy(conn net.Conn, in chan<- C.ConnContext) {
target := socks5.ParseAddrToSocksAddr(conn.LocalAddr())
conn.(*net.TCPConn).SetKeepAlive(true)
2021-06-13 17:23:10 +08:00
in <- inbound.NewSocket(target, conn, C.TPROXY)
}