1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-17 09:56:18 -05:00
v2fly/proxy/mtproto/client.go

77 lines
2.2 KiB
Go
Raw Normal View History

2018-07-04 11:48:48 -04:00
package mtproto
import (
"context"
2021-02-16 15:31:50 -05:00
"github.com/v2fly/v2ray-core/v4/common"
"github.com/v2fly/v2ray-core/v4/common/buf"
"github.com/v2fly/v2ray-core/v4/common/crypto"
"github.com/v2fly/v2ray-core/v4/common/net"
"github.com/v2fly/v2ray-core/v4/common/session"
"github.com/v2fly/v2ray-core/v4/common/task"
"github.com/v2fly/v2ray-core/v4/transport"
"github.com/v2fly/v2ray-core/v4/transport/internet"
2018-07-04 11:48:48 -04:00
)
2021-05-19 17:28:52 -04:00
type Client struct{}
2018-07-04 11:48:48 -04:00
func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
return &Client{}, nil
}
2018-11-03 07:36:29 -04:00
func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
outbound := session.OutboundFromContext(ctx)
if outbound == nil || !outbound.Target.IsValid() {
2018-07-04 11:48:48 -04:00
return newError("unknown destination.")
}
dest := outbound.Target
2018-07-04 11:48:48 -04:00
if dest.Network != net.Network_TCP {
return newError("not TCP traffic", dest)
}
conn, err := dialer.Dial(ctx, dest)
if err != nil {
return newError("failed to dial to ", dest).Base(err).AtWarning()
}
defer conn.Close()
2018-07-04 11:48:48 -04:00
sc := SessionContextFromContext(ctx)
auth := NewAuthentication(sc)
2018-07-04 11:48:48 -04:00
defer putAuthenticationObject(auth)
request := func() error {
encryptor := crypto.NewAesCTRStream(auth.EncodingKey[:], auth.EncodingNonce[:])
var header [HeaderSize]byte
encryptor.XORKeyStream(header[:], auth.Header[:])
copy(header[:56], auth.Header[:])
if _, err := conn.Write(header[:]); err != nil {
return newError("failed to write auth header").Base(err)
}
connWriter := buf.NewWriter(crypto.NewCryptionWriter(encryptor, conn))
return buf.Copy(link.Reader, connWriter)
}
response := func() error {
decryptor := crypto.NewAesCTRStream(auth.DecodingKey[:], auth.DecodingNonce[:])
connReader := buf.NewReader(crypto.NewCryptionReader(decryptor, conn))
return buf.Copy(connReader, link.Writer)
}
2021-05-19 17:28:52 -04:00
responseDoneAndCloseWriter := task.OnSuccess(response, task.Close(link.Writer))
2018-12-06 05:35:02 -05:00
if err := task.Run(ctx, request, responseDoneAndCloseWriter); err != nil {
2018-07-04 11:48:48 -04:00
return newError("connection ends").Base(err)
}
return nil
}
func init() {
common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewClient(ctx, config.(*ClientConfig))
}))
}