shadowsocks.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. }
  69. this.udpHub = udpHub
  70. this.udpServer = hub.NewUDPServer(this.packetDispatcher)
  71. }
  72. return nil
  73. }
  74. func (this *Shadowsocks) handlerUDPPayload(payload *alloc.Buffer, source v2net.Destination) {
  75. defer payload.Release()
  76. iv := payload.Value[:this.config.Cipher.IVSize()]
  77. key := this.config.Key
  78. payload.SliceFrom(this.config.Cipher.IVSize())
  79. reader, err := this.config.Cipher.NewDecodingStream(key, iv, payload)
  80. if err != nil {
  81. log.Error("Shadowsocks: Failed to create decoding stream: ", err)
  82. return
  83. }
  84. request, err := ReadRequest(reader, NewAuthenticator(HeaderKeyGenerator(key, iv)), true)
  85. if err != nil {
  86. log.Access(source, serial.StringLiteral(""), log.AccessRejected, serial.StringLiteral(err.Error()))
  87. log.Warning("Shadowsocks: Invalid request from ", source, ": ", err)
  88. return
  89. }
  90. dest := v2net.UDPDestination(request.Address, request.Port)
  91. log.Access(source, dest, log.AccessAccepted, serial.StringLiteral(""))
  92. log.Info("Shadowsocks: Tunnelling request to ", dest)
  93. packet := v2net.NewPacket(dest, request.UDPPayload, false)
  94. this.udpServer.Dispatch(source, packet, func(packet v2net.Packet) {
  95. defer packet.Chunk().Release()
  96. response := alloc.NewBuffer().Slice(0, this.config.Cipher.IVSize())
  97. defer response.Release()
  98. rand.Read(response.Value)
  99. respIv := response.Value
  100. writer, err := this.config.Cipher.NewEncodingStream(key, respIv, response)
  101. if err != nil {
  102. log.Error("Shadowsocks: Failed to create encoding stream: ", err)
  103. return
  104. }
  105. switch {
  106. case request.Address.IsIPv4():
  107. writer.Write([]byte{AddrTypeIPv4})
  108. writer.Write(request.Address.IP())
  109. case request.Address.IsIPv6():
  110. writer.Write([]byte{AddrTypeIPv6})
  111. writer.Write(request.Address.IP())
  112. case request.Address.IsDomain():
  113. writer.Write([]byte{AddrTypeDomain, byte(len(request.Address.Domain()))})
  114. writer.Write([]byte(request.Address.Domain()))
  115. }
  116. writer.Write(request.Port.Bytes())
  117. writer.Write(packet.Chunk().Value)
  118. if request.OTA {
  119. respAuth := NewAuthenticator(HeaderKeyGenerator(key, respIv))
  120. respAuth.Authenticate(response.Value, response.Value[this.config.Cipher.IVSize():])
  121. }
  122. this.udpHub.WriteTo(response.Value, source)
  123. })
  124. }
  125. func (this *Shadowsocks) handleConnection(conn *hub.TCPConn) {
  126. defer conn.Close()
  127. buffer := alloc.NewSmallBuffer()
  128. defer buffer.Release()
  129. timedReader := v2net.NewTimeOutReader(16, conn)
  130. _, err := io.ReadFull(timedReader, buffer.Value[:this.config.Cipher.IVSize()])
  131. if err != nil {
  132. log.Access(conn.RemoteAddr(), serial.StringLiteral(""), log.AccessRejected, serial.StringLiteral(err.Error()))
  133. log.Error("Shadowsocks: Failed to read IV: ", err)
  134. return
  135. }
  136. iv := buffer.Value[:this.config.Cipher.IVSize()]
  137. key := this.config.Key
  138. reader, err := this.config.Cipher.NewDecodingStream(key, iv, timedReader)
  139. if err != nil {
  140. log.Error("Shadowsocks: Failed to create decoding stream: ", err)
  141. return
  142. }
  143. request, err := ReadRequest(reader, NewAuthenticator(HeaderKeyGenerator(iv, key)), false)
  144. if err != nil {
  145. log.Access(conn.RemoteAddr(), serial.StringLiteral(""), log.AccessRejected, serial.StringLiteral(err.Error()))
  146. log.Warning("Shadowsocks: Invalid request from ", conn.RemoteAddr(), ": ", err)
  147. return
  148. }
  149. userSettings := protocol.GetUserSettings(this.config.Level)
  150. timedReader.SetTimeOut(userSettings.PayloadReadTimeout)
  151. dest := v2net.TCPDestination(request.Address, request.Port)
  152. log.Access(conn.RemoteAddr(), dest, log.AccessAccepted, serial.StringLiteral(""))
  153. log.Info("Shadowsocks: Tunnelling request to ", dest)
  154. packet := v2net.NewPacket(dest, nil, true)
  155. ray := this.packetDispatcher.DispatchToOutbound(packet)
  156. var writeFinish sync.Mutex
  157. writeFinish.Lock()
  158. go func() {
  159. if payload, ok := <-ray.InboundOutput(); ok {
  160. payload.SliceBack(16)
  161. rand.Read(payload.Value[:16])
  162. writer, err := this.config.Cipher.NewEncodingStream(key, payload.Value[:16], conn)
  163. if err != nil {
  164. log.Error("Shadowsocks: Failed to create encoding stream: ", err)
  165. return
  166. }
  167. writer.Write(payload.Value)
  168. payload.Release()
  169. v2io.ChanToRawWriter(writer, ray.InboundOutput())
  170. }
  171. writeFinish.Unlock()
  172. }()
  173. var payloadReader v2io.Reader
  174. if request.OTA {
  175. payloadAuth := NewAuthenticator(ChunkKeyGenerator(iv))
  176. payloadReader = NewChunkReader(reader, payloadAuth)
  177. } else {
  178. payloadReader = v2io.NewAdaptiveReader(reader)
  179. }
  180. v2io.ReaderToChan(ray.InboundInput(), payloadReader)
  181. close(ray.InboundInput())
  182. writeFinish.Lock()
  183. }
  184. func init() {
  185. internal.MustRegisterInboundHandlerCreator("shadowsocks",
  186. func(space app.Space, rawConfig interface{}) (proxy.InboundHandler, error) {
  187. if !space.HasApp(dispatcher.APP_ID) {
  188. return nil, internal.ErrorBadConfiguration
  189. }
  190. return NewShadowsocks(
  191. rawConfig.(*Config),
  192. space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)), nil
  193. })
  194. }