shadowsocks.go 6.6 KB

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