outbound.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. package outbound
  2. import (
  3. "crypto/md5"
  4. "crypto/rand"
  5. "io"
  6. "net"
  7. "sync"
  8. "time"
  9. "github.com/v2ray/v2ray-core/app"
  10. "github.com/v2ray/v2ray-core/common/alloc"
  11. v2crypto "github.com/v2ray/v2ray-core/common/crypto"
  12. v2io "github.com/v2ray/v2ray-core/common/io"
  13. "github.com/v2ray/v2ray-core/common/log"
  14. v2net "github.com/v2ray/v2ray-core/common/net"
  15. proto "github.com/v2ray/v2ray-core/common/protocol"
  16. "github.com/v2ray/v2ray-core/proxy"
  17. "github.com/v2ray/v2ray-core/proxy/internal"
  18. vmessio "github.com/v2ray/v2ray-core/proxy/vmess/io"
  19. "github.com/v2ray/v2ray-core/proxy/vmess/protocol"
  20. "github.com/v2ray/v2ray-core/transport/ray"
  21. )
  22. type VMessOutboundHandler struct {
  23. receiverManager *ReceiverManager
  24. }
  25. func (this *VMessOutboundHandler) Dispatch(firstPacket v2net.Packet, ray ray.OutboundRay) error {
  26. vNextAddress, vNextUser := this.receiverManager.PickReceiver()
  27. command := protocol.CmdTCP
  28. if firstPacket.Destination().IsUDP() {
  29. command = protocol.CmdUDP
  30. }
  31. request := &protocol.VMessRequest{
  32. Version: protocol.Version,
  33. User: vNextUser,
  34. Command: command,
  35. Address: firstPacket.Destination().Address(),
  36. Port: firstPacket.Destination().Port(),
  37. }
  38. if command == protocol.CmdUDP {
  39. request.Option |= protocol.OptionChunk
  40. }
  41. buffer := alloc.NewSmallBuffer()
  42. defer buffer.Release() // Buffer is released after communication finishes.
  43. io.ReadFull(rand.Reader, buffer.Value[:33]) // 16 + 16 + 1
  44. request.RequestIV = buffer.Value[:16]
  45. request.RequestKey = buffer.Value[16:32]
  46. request.ResponseHeader = buffer.Value[32]
  47. return this.startCommunicate(request, vNextAddress, ray, firstPacket)
  48. }
  49. func (this *VMessOutboundHandler) startCommunicate(request *protocol.VMessRequest, dest v2net.Destination, ray ray.OutboundRay, firstPacket v2net.Packet) error {
  50. var destIP net.IP
  51. if dest.Address().IsIPv4() || dest.Address().IsIPv6() {
  52. destIP = dest.Address().IP()
  53. } else {
  54. ips, err := net.LookupIP(dest.Address().Domain())
  55. if err != nil {
  56. return err
  57. }
  58. destIP = ips[0]
  59. }
  60. conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{
  61. IP: destIP,
  62. Port: int(dest.Port()),
  63. })
  64. if err != nil {
  65. log.Error("Failed to open ", dest, ": ", err)
  66. if ray != nil {
  67. close(ray.OutboundOutput())
  68. }
  69. return err
  70. }
  71. log.Info("VMessOut: Tunneling request to ", request.Address, " via ", dest)
  72. defer conn.Close()
  73. input := ray.OutboundInput()
  74. output := ray.OutboundOutput()
  75. var requestFinish, responseFinish sync.Mutex
  76. requestFinish.Lock()
  77. responseFinish.Lock()
  78. go this.handleRequest(conn, request, firstPacket, input, &requestFinish)
  79. go this.handleResponse(conn, request, dest, output, &responseFinish)
  80. requestFinish.Lock()
  81. conn.CloseWrite()
  82. responseFinish.Lock()
  83. return nil
  84. }
  85. func (this *VMessOutboundHandler) handleRequest(conn net.Conn, request *protocol.VMessRequest, firstPacket v2net.Packet, input <-chan *alloc.Buffer, finish *sync.Mutex) {
  86. defer finish.Unlock()
  87. aesStream, err := v2crypto.NewAesEncryptionStream(request.RequestKey[:], request.RequestIV[:])
  88. if err != nil {
  89. log.Error("VMessOut: Failed to create AES encryption stream: ", err)
  90. return
  91. }
  92. encryptRequestWriter := v2crypto.NewCryptionWriter(aesStream, conn)
  93. buffer := alloc.NewBuffer().Clear()
  94. defer buffer.Release()
  95. buffer, err = request.ToBytes(protocol.NewRandomTimestampGenerator(proto.Timestamp(time.Now().Unix()), 30), buffer)
  96. if err != nil {
  97. log.Error("VMessOut: Failed to serialize VMess request: ", err)
  98. return
  99. }
  100. // Send first packet of payload together with request, in favor of small requests.
  101. firstChunk := firstPacket.Chunk()
  102. moreChunks := firstPacket.MoreChunks()
  103. for firstChunk == nil && moreChunks {
  104. firstChunk, moreChunks = <-input
  105. }
  106. if firstChunk == nil && !moreChunks {
  107. log.Warning("VMessOut: Nothing to send. Existing...")
  108. return
  109. }
  110. if request.IsChunkStream() {
  111. vmessio.Authenticate(firstChunk)
  112. }
  113. aesStream.XORKeyStream(firstChunk.Value, firstChunk.Value)
  114. buffer.Append(firstChunk.Value)
  115. firstChunk.Release()
  116. _, err = conn.Write(buffer.Value)
  117. if err != nil {
  118. log.Error("VMessOut: Failed to write VMess request: ", err)
  119. return
  120. }
  121. if moreChunks {
  122. var streamWriter v2io.Writer = v2io.NewAdaptiveWriter(encryptRequestWriter)
  123. if request.IsChunkStream() {
  124. streamWriter = vmessio.NewAuthChunkWriter(streamWriter)
  125. }
  126. v2io.ChanToWriter(streamWriter, input)
  127. }
  128. return
  129. }
  130. func headerMatch(request *protocol.VMessRequest, responseHeader byte) bool {
  131. return request.ResponseHeader == responseHeader
  132. }
  133. func (this *VMessOutboundHandler) handleResponse(conn net.Conn, request *protocol.VMessRequest, dest v2net.Destination, output chan<- *alloc.Buffer, finish *sync.Mutex) {
  134. defer finish.Unlock()
  135. defer close(output)
  136. responseKey := md5.Sum(request.RequestKey[:])
  137. responseIV := md5.Sum(request.RequestIV[:])
  138. aesStream, err := v2crypto.NewAesDecryptionStream(responseKey[:], responseIV[:])
  139. if err != nil {
  140. log.Error("VMessOut: Failed to create AES encryption stream: ", err)
  141. return
  142. }
  143. decryptResponseReader := v2crypto.NewCryptionReader(aesStream, conn)
  144. buffer := alloc.NewSmallBuffer()
  145. defer buffer.Release()
  146. _, err = io.ReadFull(decryptResponseReader, buffer.Value[:4])
  147. if err != nil {
  148. log.Error("VMessOut: Failed to read VMess response (", buffer.Len(), " bytes): ", err)
  149. return
  150. }
  151. if !headerMatch(request, buffer.Value[0]) {
  152. log.Warning("VMessOut: unexepcted response header. The connection is probably hijacked.")
  153. return
  154. }
  155. if buffer.Value[2] != 0 {
  156. command := buffer.Value[2]
  157. dataLen := int(buffer.Value[3])
  158. _, err := io.ReadFull(decryptResponseReader, buffer.Value[:dataLen])
  159. if err != nil {
  160. log.Error("VMessOut: Failed to read response command: ", err)
  161. return
  162. }
  163. data := buffer.Value[:dataLen]
  164. go this.handleCommand(dest, command, data)
  165. }
  166. var reader v2io.Reader
  167. if request.IsChunkStream() {
  168. reader = vmessio.NewAuthChunkReader(decryptResponseReader)
  169. } else {
  170. reader = v2io.NewAdaptiveReader(decryptResponseReader)
  171. }
  172. v2io.ReaderToChan(output, reader)
  173. return
  174. }
  175. func init() {
  176. internal.MustRegisterOutboundHandlerCreator("vmess",
  177. func(space app.Space, rawConfig interface{}) (proxy.OutboundHandler, error) {
  178. vOutConfig := rawConfig.(*Config)
  179. return &VMessOutboundHandler{
  180. receiverManager: NewReceiverManager(vOutConfig.Receivers),
  181. }, nil
  182. })
  183. }