client.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package mtproto
  2. import (
  3. "context"
  4. "v2ray.com/core"
  5. "v2ray.com/core/common"
  6. "v2ray.com/core/common/buf"
  7. "v2ray.com/core/common/crypto"
  8. "v2ray.com/core/common/net"
  9. "v2ray.com/core/common/session"
  10. "v2ray.com/core/common/task"
  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 *core.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. auth := NewAuthentication()
  33. defer putAuthenticationObject(auth)
  34. request := func() error {
  35. encryptor := crypto.NewAesCTRStream(auth.EncodingKey[:], auth.EncodingNonce[:])
  36. var header [HeaderSize]byte
  37. encryptor.XORKeyStream(header[:], auth.Header[:])
  38. copy(header[:56], auth.Header[:])
  39. if _, err := conn.Write(header[:]); err != nil {
  40. return newError("failed to write auth header").Base(err)
  41. }
  42. connWriter := buf.NewWriter(crypto.NewCryptionWriter(encryptor, conn))
  43. return buf.Copy(link.Reader, connWriter)
  44. }
  45. response := func() error {
  46. decryptor := crypto.NewAesCTRStream(auth.DecodingKey[:], auth.DecodingNonce[:])
  47. connReader := buf.NewReader(crypto.NewCryptionReader(decryptor, conn))
  48. return buf.Copy(connReader, link.Writer)
  49. }
  50. var responseDoneAndCloseWriter = task.Single(response, task.OnSuccess(task.Close(link.Writer)))
  51. if err := task.Run(task.WithContext(ctx), task.Parallel(request, responseDoneAndCloseWriter))(); err != nil {
  52. return newError("connection ends").Base(err)
  53. }
  54. return nil
  55. }
  56. func init() {
  57. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  58. return NewClient(ctx, config.(*ClientConfig))
  59. }))
  60. }