shadowsocks.go 4.5 KB

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