shadowsocks.go 6.4 KB

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