Clash.Meta/transport/tuic/client.go

433 lines
9.7 KiB
Go
Raw Normal View History

2022-11-25 08:08:14 +08:00
package tuic
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"errors"
"net"
2022-11-26 23:53:59 +08:00
"runtime"
2022-11-25 08:08:14 +08:00
"sync"
2022-11-25 18:32:30 +08:00
"sync/atomic"
2022-11-25 08:08:14 +08:00
"time"
2023-04-03 21:07:52 +08:00
"github.com/Dreamacro/clash/common/buf"
2022-11-25 08:08:14 +08:00
N "github.com/Dreamacro/clash/common/net"
"github.com/Dreamacro/clash/common/pool"
2022-11-25 08:08:14 +08:00
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/log"
"github.com/metacubex/quic-go"
"github.com/zhangyunhao116/fastrand"
2022-11-25 08:08:14 +08:00
)
2022-11-25 18:32:30 +08:00
var (
ClientClosed = errors.New("tuic: client closed")
TooManyOpenStreams = errors.New("tuic: too many open streams")
)
2022-12-22 09:53:11 +08:00
type DialFunc func(ctx context.Context, dialer C.Dialer) (pc net.PacketConn, addr net.Addr, err error)
2022-11-26 23:53:59 +08:00
type ClientOption struct {
TlsConfig *tls.Config
QuicConfig *quic.Config
Host string
Token [32]byte
UdpRelayMode string
CongestionController string
ReduceRtt bool
2022-11-28 17:09:25 +08:00
RequestTimeout time.Duration
MaxUdpRelayPacketSize int
2022-11-26 21:14:56 +08:00
FastOpen bool
MaxOpenStreams int64
2022-11-26 23:53:59 +08:00
}
type clientImpl struct {
2022-11-26 23:53:59 +08:00
*ClientOption
udp bool
2022-11-25 08:08:14 +08:00
quicConn quic.Connection
connMutex sync.Mutex
openStreams atomic.Int64
2022-11-28 17:09:25 +08:00
closed atomic.Bool
2022-11-25 18:32:30 +08:00
2022-11-25 08:08:14 +08:00
udpInputMap sync.Map
2022-11-26 23:53:59 +08:00
// only ready for PoolClient
2022-12-22 09:53:11 +08:00
dialerRef C.Dialer
2022-11-26 23:53:59 +08:00
lastVisited time.Time
2022-11-25 08:08:14 +08:00
}
2022-12-22 09:53:11 +08:00
func (t *clientImpl) getQuicConn(ctx context.Context, dialer C.Dialer, dialFn DialFunc) (quic.Connection, error) {
2022-11-25 08:08:14 +08:00
t.connMutex.Lock()
defer t.connMutex.Unlock()
if t.quicConn != nil {
return t.quicConn, nil
}
2022-12-22 09:53:11 +08:00
pc, addr, err := dialFn(ctx, dialer)
2022-11-25 08:08:14 +08:00
if err != nil {
return nil, err
}
var quicConn quic.Connection
if t.ReduceRtt {
quicConn, err = quic.DialEarlyContext(ctx, pc, addr, t.Host, t.TlsConfig, t.QuicConfig)
} else {
quicConn, err = quic.DialContext(ctx, pc, addr, t.Host, t.TlsConfig, t.QuicConfig)
}
if err != nil {
return nil, err
}
2022-11-28 17:09:25 +08:00
SetCongestionController(quicConn, t.CongestionController)
2022-11-28 17:09:25 +08:00
go func() {
_ = t.sendAuthentication(quicConn)
}()
if t.udp {
go func() {
_ = t.parseUDP(quicConn)
2022-11-25 08:08:14 +08:00
}()
}
2022-11-28 17:09:25 +08:00
t.quicConn = quicConn
t.openStreams.Store(0)
return quicConn, nil
}
func (t *clientImpl) sendAuthentication(quicConn quic.Connection) (err error) {
2022-11-28 17:09:25 +08:00
defer func() {
t.deferQuicConn(quicConn, err)
}()
stream, err := quicConn.OpenUniStream()
if err != nil {
return err
}
buf := pool.GetBuffer()
defer pool.PutBuffer(buf)
err = NewAuthenticate(t.Token).WriteTo(buf)
if err != nil {
return err
}
_, err = buf.WriteTo(stream)
if err != nil {
return err
}
err = stream.Close()
if err != nil {
return
}
return nil
}
func (t *clientImpl) parseUDP(quicConn quic.Connection) (err error) {
2022-11-28 17:09:25 +08:00
defer func() {
t.deferQuicConn(quicConn, err)
}()
switch t.UdpRelayMode {
case "quic":
for {
var stream quic.ReceiveStream
stream, err = quicConn.AcceptUniStream(context.Background())
if err != nil {
return err
}
go func() (err error) {
var assocId uint32
defer func() {
t.deferQuicConn(quicConn, err)
if err != nil && assocId != 0 {
if val, ok := t.udpInputMap.LoadAndDelete(assocId); ok {
if conn, ok := val.(net.Conn); ok {
_ = conn.Close()
2022-11-25 08:08:14 +08:00
}
}
}
2022-11-28 17:09:25 +08:00
stream.CancelRead(0)
2022-11-25 08:08:14 +08:00
}()
2022-11-28 17:09:25 +08:00
reader := bufio.NewReader(stream)
packet, err := ReadPacket(reader)
2022-11-25 08:08:14 +08:00
if err != nil {
2022-11-28 17:09:25 +08:00
return
2022-11-25 08:08:14 +08:00
}
2022-11-28 17:09:25 +08:00
assocId = packet.ASSOC_ID
if val, ok := t.udpInputMap.Load(assocId); ok {
if conn, ok := val.(net.Conn); ok {
writer := bufio.NewWriterSize(conn, packet.BytesLen())
_ = packet.WriteTo(writer)
_ = writer.Flush()
2022-11-25 08:08:14 +08:00
}
2022-11-28 17:09:25 +08:00
}
return
}()
}
default: // native
for {
var message []byte
message, err = quicConn.ReceiveMessage()
if err != nil {
return err
}
go func() (err error) {
var assocId uint32
defer func() {
t.deferQuicConn(quicConn, err)
if err != nil && assocId != 0 {
if val, ok := t.udpInputMap.LoadAndDelete(assocId); ok {
if conn, ok := val.(net.Conn); ok {
_ = conn.Close()
}
2022-11-25 08:08:14 +08:00
}
}
}()
2022-11-28 17:09:25 +08:00
buffer := bytes.NewBuffer(message)
packet, err := ReadPacket(buffer)
if err != nil {
return
}
assocId = packet.ASSOC_ID
if val, ok := t.udpInputMap.Load(assocId); ok {
if conn, ok := val.(net.Conn); ok {
_, _ = conn.Write(message)
}
}
return
}()
2022-11-25 08:08:14 +08:00
}
2022-11-25 17:15:45 +08:00
}
2022-11-25 08:08:14 +08:00
}
func (t *clientImpl) deferQuicConn(quicConn quic.Connection, err error) {
2022-11-25 08:08:14 +08:00
var netError net.Error
if err != nil && errors.As(err, &netError) {
t.forceClose(quicConn, err)
2022-11-25 08:08:14 +08:00
}
}
func (t *clientImpl) forceClose(quicConn quic.Connection, err error) {
t.connMutex.Lock()
defer t.connMutex.Unlock()
if quicConn == nil {
quicConn = t.quicConn
2022-11-28 17:09:25 +08:00
}
2022-11-25 11:32:05 +08:00
if quicConn != nil {
if quicConn == t.quicConn {
t.quicConn = nil
}
2022-11-25 11:32:05 +08:00
}
errStr := ""
if err != nil {
errStr = err.Error()
}
if quicConn != nil {
_ = quicConn.CloseWithError(ProtocolError, errStr)
}
udpInputMap := &t.udpInputMap
udpInputMap.Range(func(key, value any) bool {
if conn, ok := value.(net.Conn); ok {
_ = conn.Close()
}
udpInputMap.Delete(key)
return true
})
2022-11-25 11:32:05 +08:00
}
func (t *clientImpl) Close() {
2022-11-28 17:09:25 +08:00
t.closed.Store(true)
if t.openStreams.Load() == 0 {
t.forceClose(nil, ClientClosed)
2022-11-28 17:09:25 +08:00
}
}
2022-12-22 09:53:11 +08:00
func (t *clientImpl) DialContextWithDialer(ctx context.Context, metadata *C.Metadata, dialer C.Dialer, dialFn DialFunc) (net.Conn, error) {
quicConn, err := t.getQuicConn(ctx, dialer, dialFn)
2022-11-25 08:08:14 +08:00
if err != nil {
return nil, err
}
2022-11-26 23:53:59 +08:00
openStreams := t.openStreams.Add(1)
if openStreams >= t.MaxOpenStreams {
2022-11-26 23:53:59 +08:00
t.openStreams.Add(-1)
2022-11-25 18:32:30 +08:00
return nil, TooManyOpenStreams
}
2022-11-25 17:15:45 +08:00
stream, err := func() (stream *quicStreamConn, err error) {
defer func() {
t.deferQuicConn(quicConn, err)
}()
buf := pool.GetBuffer()
defer pool.PutBuffer(buf)
err = NewConnect(NewAddress(metadata)).WriteTo(buf)
if err != nil {
return nil, err
}
2022-11-25 17:15:45 +08:00
quicStream, err := quicConn.OpenStream()
if err != nil {
return nil, err
}
2022-11-25 19:14:09 +08:00
stream = &quicStreamConn{
Stream: quicStream,
lAddr: quicConn.LocalAddr(),
rAddr: quicConn.RemoteAddr(),
2022-11-28 17:09:25 +08:00
closeDeferFn: func() {
time.AfterFunc(C.DefaultTCPTimeout, func() {
openStreams := t.openStreams.Add(-1)
if openStreams == 0 && t.closed.Load() {
t.forceClose(quicConn, ClientClosed)
2022-11-28 17:09:25 +08:00
}
})
},
2022-11-25 19:14:09 +08:00
}
_, err = buf.WriteTo(stream)
if err != nil {
_ = stream.Close()
return nil, err
}
return stream, err
2022-11-25 08:08:14 +08:00
}()
2022-11-25 12:10:33 +08:00
if err != nil {
return nil, err
}
2022-11-27 16:38:41 +08:00
conn := &earlyConn{BufferedConn: N.NewBufferedConn(stream), RequestTimeout: t.RequestTimeout}
2022-11-26 21:14:56 +08:00
if !t.FastOpen {
err = conn.Response()
if err != nil {
return nil, err
}
}
return conn, nil
}
type earlyConn struct {
*N.BufferedConn
resOnce sync.Once
resErr error
2022-11-27 16:38:41 +08:00
2022-11-28 17:09:25 +08:00
RequestTimeout time.Duration
2022-11-26 21:14:56 +08:00
}
func (conn *earlyConn) ReaderReplaceable() bool {
return false
}
2022-11-26 21:14:56 +08:00
func (conn *earlyConn) response() error {
2022-11-27 16:38:41 +08:00
if conn.RequestTimeout > 0 {
2022-11-28 17:09:25 +08:00
_ = conn.SetReadDeadline(time.Now().Add(conn.RequestTimeout))
2022-11-27 16:38:41 +08:00
}
2022-11-25 08:08:14 +08:00
response, err := ReadResponse(conn)
if err != nil {
2022-11-25 16:06:56 +08:00
_ = conn.Close()
2022-11-26 21:14:56 +08:00
return err
2022-11-25 08:08:14 +08:00
}
if response.IsFailed() {
2022-11-25 16:06:56 +08:00
_ = conn.Close()
2022-11-26 21:14:56 +08:00
return errors.New("connect failed")
2022-11-25 08:08:14 +08:00
}
2022-11-26 21:14:56 +08:00
_ = conn.SetReadDeadline(time.Time{})
return nil
}
func (conn *earlyConn) Response() error {
conn.resOnce.Do(func() {
conn.resErr = conn.response()
})
return conn.resErr
}
func (conn *earlyConn) Read(b []byte) (n int, err error) {
err = conn.Response()
if err != nil {
return 0, err
}
return conn.BufferedConn.Read(b)
2022-11-25 08:08:14 +08:00
}
2023-04-03 21:07:52 +08:00
func (conn *earlyConn) ReadBuffer(buffer *buf.Buffer) (err error) {
err = conn.Response()
if err != nil {
return err
}
return conn.BufferedConn.ReadBuffer(buffer)
}
2022-12-22 09:53:11 +08:00
func (t *clientImpl) ListenPacketWithDialer(ctx context.Context, metadata *C.Metadata, dialer C.Dialer, dialFn DialFunc) (net.PacketConn, error) {
quicConn, err := t.getQuicConn(ctx, dialer, dialFn)
2022-11-25 08:08:14 +08:00
if err != nil {
return nil, err
}
2022-11-26 23:53:59 +08:00
openStreams := t.openStreams.Add(1)
if openStreams >= t.MaxOpenStreams {
2022-11-26 23:53:59 +08:00
t.openStreams.Add(-1)
2022-11-25 20:14:05 +08:00
return nil, TooManyOpenStreams
}
2022-11-25 08:08:14 +08:00
pipe1, pipe2 := net.Pipe()
var connId uint32
for {
connId = fastrand.Uint32()
2022-11-25 08:08:14 +08:00
_, loaded := t.udpInputMap.LoadOrStore(connId, pipe1)
if !loaded {
break
}
}
pc := &quicStreamPacketConn{
2022-11-28 17:09:25 +08:00
connId: connId,
quicConn: quicConn,
inputConn: N.NewBufferedConn(pipe2),
udpRelayMode: t.UdpRelayMode,
maxUdpRelayPacketSize: t.MaxUdpRelayPacketSize,
deferQuicConnFn: t.deferQuicConn,
closeDeferFn: func() {
t.udpInputMap.Delete(connId)
time.AfterFunc(C.DefaultUDPTimeout, func() {
openStreams := t.openStreams.Add(-1)
if openStreams == 0 && t.closed.Load() {
t.forceClose(quicConn, ClientClosed)
2022-11-28 17:09:25 +08:00
}
})
},
2022-11-25 08:08:14 +08:00
}
return pc, nil
}
type Client struct {
*clientImpl // use an independent pointer to let Finalizer can work no matter somewhere handle an influence in clientImpl inner
}
2022-12-22 09:53:11 +08:00
func (t *Client) DialContextWithDialer(ctx context.Context, metadata *C.Metadata, dialer C.Dialer, dialFn DialFunc) (net.Conn, error) {
conn, err := t.clientImpl.DialContextWithDialer(ctx, metadata, dialer, dialFn)
if err != nil {
return nil, err
}
return N.NewRefConn(conn, t), err
}
2022-12-22 09:53:11 +08:00
func (t *Client) ListenPacketWithDialer(ctx context.Context, metadata *C.Metadata, dialer C.Dialer, dialFn DialFunc) (net.PacketConn, error) {
pc, err := t.clientImpl.ListenPacketWithDialer(ctx, metadata, dialer, dialFn)
if err != nil {
return nil, err
}
return N.NewRefPacketConn(pc, t), nil
}
func (t *Client) forceClose() {
t.clientImpl.forceClose(nil, ClientClosed)
}
2022-11-26 23:53:59 +08:00
func NewClient(clientOption *ClientOption, udp bool) *Client {
ci := &clientImpl{
2022-11-26 23:53:59 +08:00
ClientOption: clientOption,
udp: udp,
}
c := &Client{ci}
2022-11-26 23:53:59 +08:00
runtime.SetFinalizer(c, closeClient)
log.Debugln("New Tuic Client at %p", c)
2022-11-26 23:53:59 +08:00
return c
}
func closeClient(client *Client) {
log.Debugln("Close Tuic Client at %p", client)
client.forceClose()
2022-11-26 23:53:59 +08:00
}