shadowsocks.go 6.4 KB

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