shadowsocks.go 6.6 KB

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