client.go 2.1 KB

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