outbound.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. package outbound
  2. import (
  3. "io"
  4. "sync"
  5. "github.com/v2ray/v2ray-core/app"
  6. "github.com/v2ray/v2ray-core/common/alloc"
  7. v2io "github.com/v2ray/v2ray-core/common/io"
  8. "github.com/v2ray/v2ray-core/common/log"
  9. v2net "github.com/v2ray/v2ray-core/common/net"
  10. "github.com/v2ray/v2ray-core/common/protocol"
  11. "github.com/v2ray/v2ray-core/common/protocol/raw"
  12. "github.com/v2ray/v2ray-core/common/retry"
  13. "github.com/v2ray/v2ray-core/proxy"
  14. "github.com/v2ray/v2ray-core/proxy/internal"
  15. vmessio "github.com/v2ray/v2ray-core/proxy/vmess/io"
  16. "github.com/v2ray/v2ray-core/transport/internet"
  17. "github.com/v2ray/v2ray-core/transport/ray"
  18. )
  19. type VMessOutboundHandler struct {
  20. receiverManager *ReceiverManager
  21. meta *proxy.OutboundHandlerMeta
  22. }
  23. func (this *VMessOutboundHandler) Dispatch(target v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error {
  24. defer ray.OutboundInput().Release()
  25. defer ray.OutboundOutput().Close()
  26. var rec *Receiver
  27. var conn internet.Connection
  28. err := retry.Timed(5, 100).On(func() error {
  29. rec = this.receiverManager.PickReceiver()
  30. rawConn, err := internet.Dial(this.meta.Address, rec.Destination, this.meta.StreamSettings)
  31. if err != nil {
  32. return err
  33. }
  34. conn = rawConn
  35. return nil
  36. })
  37. if err != nil {
  38. log.Error("Failed to find an available destination:", err)
  39. return err
  40. }
  41. log.Info("VMessOut: Tunneling request to ", target, " via ", rec.Destination)
  42. command := protocol.RequestCommandTCP
  43. if target.IsUDP() {
  44. command = protocol.RequestCommandUDP
  45. }
  46. request := &protocol.RequestHeader{
  47. Version: raw.Version,
  48. User: rec.PickUser(),
  49. Command: command,
  50. Address: target.Address(),
  51. Port: target.Port(),
  52. Option: protocol.RequestOptionChunkStream,
  53. }
  54. defer conn.Close()
  55. conn.SetReusable(true)
  56. if conn.Reusable() { // Conn reuse may be disabled on transportation layer
  57. request.Option.Set(protocol.RequestOptionConnectionReuse)
  58. }
  59. input := ray.OutboundInput()
  60. output := ray.OutboundOutput()
  61. var requestFinish, responseFinish sync.Mutex
  62. requestFinish.Lock()
  63. responseFinish.Lock()
  64. session := raw.NewClientSession(protocol.DefaultIDHash)
  65. go this.handleRequest(session, conn, request, payload, input, &requestFinish)
  66. go this.handleResponse(session, conn, request, rec.Destination, output, &responseFinish)
  67. requestFinish.Lock()
  68. responseFinish.Lock()
  69. return nil
  70. }
  71. func (this *VMessOutboundHandler) handleRequest(session *raw.ClientSession, conn internet.Connection, request *protocol.RequestHeader, payload *alloc.Buffer, input v2io.Reader, finish *sync.Mutex) {
  72. defer finish.Unlock()
  73. writer := v2io.NewBufferedWriter(conn)
  74. defer writer.Release()
  75. session.EncodeRequestHeader(request, writer)
  76. bodyWriter := session.EncodeRequestBody(writer)
  77. var streamWriter v2io.Writer = v2io.NewAdaptiveWriter(bodyWriter)
  78. if request.Option.Has(protocol.RequestOptionChunkStream) {
  79. streamWriter = vmessio.NewAuthChunkWriter(streamWriter)
  80. }
  81. if err := streamWriter.Write(payload); err != nil {
  82. conn.SetReusable(false)
  83. }
  84. writer.SetCached(false)
  85. err := v2io.Pipe(input, streamWriter)
  86. if err != io.EOF {
  87. conn.SetReusable(false)
  88. }
  89. if request.Option.Has(protocol.RequestOptionChunkStream) {
  90. err := streamWriter.Write(alloc.NewSmallBuffer().Clear())
  91. if err != nil {
  92. conn.SetReusable(false)
  93. }
  94. }
  95. streamWriter.Release()
  96. return
  97. }
  98. func (this *VMessOutboundHandler) handleResponse(session *raw.ClientSession, conn internet.Connection, request *protocol.RequestHeader, dest v2net.Destination, output v2io.Writer, finish *sync.Mutex) {
  99. defer finish.Unlock()
  100. reader := v2io.NewBufferedReader(conn)
  101. defer reader.Release()
  102. header, err := session.DecodeResponseHeader(reader)
  103. if err != nil {
  104. conn.SetReusable(false)
  105. log.Warning("VMessOut: Failed to read response: ", err)
  106. return
  107. }
  108. go this.handleCommand(dest, header.Command)
  109. if !header.Option.Has(protocol.ResponseOptionConnectionReuse) {
  110. conn.SetReusable(false)
  111. }
  112. reader.SetCached(false)
  113. decryptReader := session.DecodeResponseBody(reader)
  114. var bodyReader v2io.Reader
  115. if request.Option.Has(protocol.RequestOptionChunkStream) {
  116. bodyReader = vmessio.NewAuthChunkReader(decryptReader)
  117. } else {
  118. bodyReader = v2io.NewAdaptiveReader(decryptReader)
  119. }
  120. err = v2io.Pipe(bodyReader, output)
  121. if err != io.EOF {
  122. conn.SetReusable(false)
  123. }
  124. bodyReader.Release()
  125. return
  126. }
  127. type Factory struct{}
  128. func (this *Factory) StreamCapability() internet.StreamConnectionType {
  129. return internet.StreamConnectionTypeRawTCP | internet.StreamConnectionTypeTCP
  130. }
  131. func (this *Factory) Create(space app.Space, rawConfig interface{}, meta *proxy.OutboundHandlerMeta) (proxy.OutboundHandler, error) {
  132. vOutConfig := rawConfig.(*Config)
  133. handler := &VMessOutboundHandler{
  134. receiverManager: NewReceiverManager(vOutConfig.Receivers),
  135. meta: meta,
  136. }
  137. return handler, nil
  138. }
  139. func init() {
  140. internal.MustRegisterOutboundHandlerCreator("vmess", new(Factory))
  141. }