clash/listener/tunnel/tcp.go

76 lines
1.4 KiB
Go
Raw Normal View History

package tunnel
import (
2022-11-18 14:57:33 +00:00
"fmt"
"net"
"github.com/Dreamacro/clash/adapter/inbound"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/transport/socks5"
)
type Listener struct {
2022-11-18 14:57:33 +00:00
listener net.Listener
addr string
target socks5.Addr
proxy string
closed bool
}
2022-11-18 14:57:33 +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()
}
2022-12-05 09:03:12 +00:00
func (l *Listener) handleTCP(conn net.Conn, in chan<- C.ConnContext, additions ...inbound.Addition) {
2022-11-18 14:57:33 +00:00
conn.(*net.TCPConn).SetKeepAlive(true)
2022-12-05 09:03:12 +00:00
ctx := inbound.NewSocket(l.target, conn, C.TUNNEL, additions...)
2022-11-18 14:57:33 +00:00
ctx.Metadata().SpecialProxy = l.proxy
in <- ctx
}
2022-12-05 09:03:12 +00:00
func New(addr, target, proxy string, in chan<- C.ConnContext, additions ...inbound.Addition) (*Listener, error) {
2022-11-18 14:57:33 +00:00
l, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
2022-11-18 14:57:33 +00:00
targetAddr := socks5.ParseAddr(target)
if targetAddr == nil {
return nil, fmt.Errorf("invalid target address %s", target)
}
2022-11-18 14:57:33 +00:00
rl := &Listener{
listener: l,
target: targetAddr,
proxy: proxy,
addr: addr,
}
2022-11-18 14:57:33 +00:00
go func() {
for {
c, err := l.Accept()
if err != nil {
if rl.closed {
break
}
continue
}
2022-12-05 09:03:12 +00:00
go rl.handleTCP(c, in, additions...)
2022-11-18 14:57:33 +00:00
}
}()
return rl, nil
}