shadowsocks.go 6.0 KB

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