mihomo/listener/tproxy/tproxy.go

83 lines
1.6 KiB
Go
Raw Permalink Normal View History

2021-06-13 17:23:10 +08:00
package tproxy
import (
"net"
2023-11-03 21:01:45 +08:00
"github.com/metacubex/mihomo/adapter/inbound"
N "github.com/metacubex/mihomo/common/net"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/transport/socks5"
)
2021-06-13 17:23:10 +08:00
type Listener struct {
listener net.Listener
addr string
closed bool
}
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()
}
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())
N.TCPKeepAlive(conn)
tunnel.HandleTCPConn(inbound.NewSocket(target, conn, C.TPROXY, additions...))
2021-08-01 00:35:37 +08:00
}
func New(addr string, tunnel C.Tunnel, additions ...inbound.Addition) (*Listener, error) {
if len(additions) == 0 {
additions = []inbound.Addition{
inbound.WithInName("DEFAULT-TPROXY"),
inbound.WithSpecialRules(""),
}
}
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,
addr: addr,
}
go func() {
for {
c, err := l.Accept()
if err != nil {
if rl.closed {
break
}
continue
}
go rl.handleTProxy(c, tunnel, additions...)
}
}()
return rl, nil
}