github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/proxy/mtproto/client.go (about)

     1  package mtproto
     2  
     3  import (
     4  	"context"
     5  
     6  	"v2ray.com/core/common"
     7  	"v2ray.com/core/common/buf"
     8  	"v2ray.com/core/common/crypto"
     9  	"v2ray.com/core/common/net"
    10  	"v2ray.com/core/common/session"
    11  	"v2ray.com/core/common/task"
    12  	"v2ray.com/core/transport"
    13  	"v2ray.com/core/transport/internet"
    14  )
    15  
    16  type Client struct {
    17  }
    18  
    19  func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
    20  	return &Client{}, nil
    21  }
    22  
    23  func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
    24  	outbound := session.OutboundFromContext(ctx)
    25  	if outbound == nil || !outbound.Target.IsValid() {
    26  		return newError("unknown destination.")
    27  	}
    28  	dest := outbound.Target
    29  	if dest.Network != net.Network_TCP {
    30  		return newError("not TCP traffic", dest)
    31  	}
    32  
    33  	conn, err := dialer.Dial(ctx, dest)
    34  	if err != nil {
    35  		return newError("failed to dial to ", dest).Base(err).AtWarning()
    36  	}
    37  	defer conn.Close() // nolint: errcheck
    38  
    39  	sc := SessionContextFromContext(ctx)
    40  	auth := NewAuthentication(sc)
    41  	defer putAuthenticationObject(auth)
    42  
    43  	request := func() error {
    44  		encryptor := crypto.NewAesCTRStream(auth.EncodingKey[:], auth.EncodingNonce[:])
    45  
    46  		var header [HeaderSize]byte
    47  		encryptor.XORKeyStream(header[:], auth.Header[:])
    48  		copy(header[:56], auth.Header[:])
    49  
    50  		if _, err := conn.Write(header[:]); err != nil {
    51  			return newError("failed to write auth header").Base(err)
    52  		}
    53  
    54  		connWriter := buf.NewWriter(crypto.NewCryptionWriter(encryptor, conn))
    55  		return buf.Copy(link.Reader, connWriter)
    56  	}
    57  
    58  	response := func() error {
    59  		decryptor := crypto.NewAesCTRStream(auth.DecodingKey[:], auth.DecodingNonce[:])
    60  
    61  		connReader := buf.NewReader(crypto.NewCryptionReader(decryptor, conn))
    62  		return buf.Copy(connReader, link.Writer)
    63  	}
    64  
    65  	var responseDoneAndCloseWriter = task.OnSuccess(response, task.Close(link.Writer))
    66  	if err := task.Run(ctx, request, responseDoneAndCloseWriter); err != nil {
    67  		return newError("connection ends").Base(err)
    68  	}
    69  
    70  	return nil
    71  }
    72  
    73  func init() {
    74  	common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
    75  		return NewClient(ctx, config.(*ClientConfig))
    76  	}))
    77  }