shadowsocks.go 5.2 KB

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