shadowsocks.go 4.6 KB

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