shadowsocks.go 4.5 KB

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