2022-11-11 20:56:08 +08:00
|
|
|
package tunnel
|
|
|
|
|
|
|
|
import (
|
2022-11-18 22:57:33 +08:00
|
|
|
"fmt"
|
2022-11-11 20:56:08 +08:00
|
|
|
"net"
|
|
|
|
|
|
|
|
"github.com/Dreamacro/clash/adapter/inbound"
|
2023-09-02 16:25:55 +08:00
|
|
|
N "github.com/Dreamacro/clash/common/net"
|
2022-11-11 20:56:08 +08:00
|
|
|
C "github.com/Dreamacro/clash/constant"
|
|
|
|
"github.com/Dreamacro/clash/transport/socks5"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Listener struct {
|
2022-11-18 22:57:33 +08:00
|
|
|
listener net.Listener
|
|
|
|
addr string
|
|
|
|
target socks5.Addr
|
|
|
|
proxy string
|
|
|
|
closed bool
|
2022-11-11 20:56:08 +08:00
|
|
|
}
|
|
|
|
|
2022-11-18 22:57:33 +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) handleTCP(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) {
|
2023-09-02 16:25:55 +08:00
|
|
|
N.TCPKeepAlive(conn)
|
2022-12-05 17:03:12 +08:00
|
|
|
ctx := inbound.NewSocket(l.target, conn, C.TUNNEL, additions...)
|
2022-11-18 22:57:33 +08:00
|
|
|
ctx.Metadata().SpecialProxy = l.proxy
|
2023-09-28 18:59:31 +08:00
|
|
|
tunnel.HandleTCPConn(ctx)
|
2022-11-18 22:57:33 +08:00
|
|
|
}
|
|
|
|
|
2023-09-28 18:59:31 +08:00
|
|
|
func New(addr, target, proxy string, tunnel C.Tunnel, additions ...inbound.Addition) (*Listener, error) {
|
2023-02-24 14:19:50 +08:00
|
|
|
l, err := inbound.Listen("tcp", addr)
|
2022-11-11 20:56:08 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-11-18 22:57:33 +08:00
|
|
|
targetAddr := socks5.ParseAddr(target)
|
|
|
|
if targetAddr == nil {
|
|
|
|
return nil, fmt.Errorf("invalid target address %s", target)
|
2022-11-11 20:56:08 +08:00
|
|
|
}
|
|
|
|
|
2022-11-18 22:57:33 +08:00
|
|
|
rl := &Listener{
|
|
|
|
listener: l,
|
|
|
|
target: targetAddr,
|
|
|
|
proxy: proxy,
|
|
|
|
addr: addr,
|
2022-11-11 20:56:08 +08:00
|
|
|
}
|
|
|
|
|
2022-11-18 22:57:33 +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.handleTCP(c, tunnel, additions...)
|
2022-11-18 22:57:33 +08:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return rl, nil
|
2022-11-11 20:56:08 +08:00
|
|
|
}
|