shadowsocks.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. // R.I.P Shadowsocks
  2. package shadowsocks
  3. import (
  4. "crypto/rand"
  5. "io"
  6. "sync"
  7. "github.com/v2ray/v2ray-core/app"
  8. "github.com/v2ray/v2ray-core/common/alloc"
  9. v2io "github.com/v2ray/v2ray-core/common/io"
  10. "github.com/v2ray/v2ray-core/common/log"
  11. v2net "github.com/v2ray/v2ray-core/common/net"
  12. "github.com/v2ray/v2ray-core/proxy"
  13. "github.com/v2ray/v2ray-core/proxy/internal"
  14. "github.com/v2ray/v2ray-core/transport/hub"
  15. )
  16. type Shadowsocks struct {
  17. space app.Space
  18. config *Config
  19. port v2net.Port
  20. accepting bool
  21. tcpHub *hub.TCPHub
  22. udpHub *hub.UDPHub
  23. }
  24. func (this *Shadowsocks) Port() v2net.Port {
  25. return this.port
  26. }
  27. func (this *Shadowsocks) Close() {
  28. this.accepting = false
  29. if this.tcpHub != nil {
  30. this.tcpHub.Close()
  31. this.tcpHub = nil
  32. }
  33. if this.udpHub != nil {
  34. this.udpHub.Close()
  35. this.udpHub = nil
  36. }
  37. }
  38. func (this *Shadowsocks) Listen(port v2net.Port) error {
  39. if this.accepting {
  40. if this.port == port {
  41. return nil
  42. } else {
  43. return proxy.ErrorAlreadyListening
  44. }
  45. }
  46. this.accepting = true
  47. tcpHub, err := hub.ListenTCP(port, this.handleConnection)
  48. if err != nil {
  49. log.Error("Shadowsocks: Failed to listen TCP on port ", port, ": ", err)
  50. return err
  51. }
  52. this.tcpHub = tcpHub
  53. if this.config.UDP {
  54. udpHub, err := hub.ListenUDP(port, this.handlerUDPPayload)
  55. if err != nil {
  56. log.Error("Shadowsocks: Failed to listen UDP on port ", port, ": ", err)
  57. }
  58. this.udpHub = udpHub
  59. }
  60. return nil
  61. }
  62. func (this *Shadowsocks) handlerUDPPayload(payload *alloc.Buffer, dest v2net.Destination) {
  63. defer payload.Release()
  64. iv := payload.Value[:this.config.Cipher.IVSize()]
  65. key := this.config.Key
  66. payload.SliceFrom(this.config.Cipher.IVSize())
  67. reader, err := this.config.Cipher.NewDecodingStream(key, iv, payload)
  68. if err != nil {
  69. log.Error("Shadowsocks: Failed to create decoding stream: ", err)
  70. return
  71. }
  72. request, err := ReadRequest(reader, NewAuthenticator(HeaderKeyGenerator(key, iv)))
  73. if err != nil {
  74. return
  75. }
  76. buffer, _ := v2io.ReadFrom(reader, nil)
  77. packet := v2net.NewPacket(v2net.TCPDestination(request.Address, request.Port), buffer, false)
  78. ray := this.space.PacketDispatcher().DispatchToOutbound(packet)
  79. close(ray.InboundInput())
  80. for respChunk := range ray.InboundOutput() {
  81. response := alloc.NewBuffer().Slice(0, this.config.Cipher.IVSize())
  82. rand.Read(response.Value)
  83. respIv := response.Value
  84. writer, err := this.config.Cipher.NewEncodingStream(key, respIv, response)
  85. if err != nil {
  86. log.Error("Shadowsocks: Failed to create encoding stream: ", err)
  87. return
  88. }
  89. switch {
  90. case request.Address.IsIPv4():
  91. writer.Write([]byte{AddrTypeIPv4})
  92. writer.Write(request.Address.IP())
  93. case request.Address.IsIPv6():
  94. writer.Write([]byte{AddrTypeIPv6})
  95. writer.Write(request.Address.IP())
  96. case request.Address.IsDomain():
  97. writer.Write([]byte{AddrTypeDomain, byte(len(request.Address.Domain()))})
  98. writer.Write([]byte(request.Address.Domain()))
  99. }
  100. writer.Write(request.Port.Bytes())
  101. writer.Write(respChunk.Value)
  102. respChunk.Release()
  103. if request.OTA {
  104. respAuth := NewAuthenticator(HeaderKeyGenerator(key, respIv))
  105. respAuth.Authenticate(buffer.Value, buffer.Value[this.config.Cipher.IVSize():])
  106. }
  107. this.udpHub.WriteTo(response.Value, dest)
  108. response.Release()
  109. }
  110. }
  111. func (this *Shadowsocks) handleConnection(conn *hub.TCPConn) {
  112. defer conn.Close()
  113. buffer := alloc.NewSmallBuffer()
  114. defer buffer.Release()
  115. _, err := io.ReadFull(conn, buffer.Value[:this.config.Cipher.IVSize()])
  116. if err != nil {
  117. log.Error("Shadowsocks: Failed to read IV: ", err)
  118. return
  119. }
  120. iv := buffer.Value[:this.config.Cipher.IVSize()]
  121. key := this.config.Key
  122. reader, err := this.config.Cipher.NewDecodingStream(key, iv, conn)
  123. if err != nil {
  124. log.Error("Shadowsocks: Failed to create decoding stream: ", err)
  125. return
  126. }
  127. request, err := ReadRequest(reader, NewAuthenticator(HeaderKeyGenerator(key, iv)))
  128. if err != nil {
  129. return
  130. }
  131. packet := v2net.NewPacket(v2net.TCPDestination(request.Address, request.Port), nil, true)
  132. ray := this.space.PacketDispatcher().DispatchToOutbound(packet)
  133. var writeFinish sync.Mutex
  134. writeFinish.Lock()
  135. go func() {
  136. firstChunk := alloc.NewBuffer().Slice(0, this.config.Cipher.IVSize())
  137. defer firstChunk.Release()
  138. writer, err := this.config.Cipher.NewEncodingStream(key, firstChunk.Value, conn)
  139. if err != nil {
  140. log.Error("Shadowsocks: Failed to create encoding stream: ", err)
  141. return
  142. }
  143. if payload, ok := <-ray.InboundOutput(); ok {
  144. firstChunk.Append(payload.Value)
  145. payload.Release()
  146. writer.Write(firstChunk.Value)
  147. v2io.ChanToWriter(writer, ray.InboundOutput())
  148. }
  149. writeFinish.Unlock()
  150. }()
  151. var payloadReader v2io.Reader
  152. if request.OTA {
  153. payloadAuth := NewAuthenticator(ChunkKeyGenerator(iv))
  154. payloadReader = v2io.NewAuthenticationReader(v2io.NewChunkReader(reader), payloadAuth, true)
  155. } else {
  156. payloadReader = v2io.NewAdaptiveReader(reader)
  157. }
  158. v2io.ReaderToChan(ray.InboundInput(), payloadReader)
  159. close(ray.InboundInput())
  160. writeFinish.Lock()
  161. }
  162. func init() {
  163. internal.MustRegisterInboundHandlerCreator("shadowsocks",
  164. func(space app.Space, rawConfig interface{}) (proxy.InboundHandler, error) {
  165. config := rawConfig.(*Config)
  166. return &Shadowsocks{
  167. space: space,
  168. config: config,
  169. }, nil
  170. })
  171. }