server.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // R.I.P Shadowsocks
  2. package shadowsocks
  3. import (
  4. "crypto/rand"
  5. "io"
  6. "sync"
  7. "v2ray.com/core/app"
  8. "v2ray.com/core/app/dispatcher"
  9. "v2ray.com/core/common"
  10. "v2ray.com/core/common/alloc"
  11. "v2ray.com/core/common/crypto"
  12. v2io "v2ray.com/core/common/io"
  13. "v2ray.com/core/common/log"
  14. v2net "v2ray.com/core/common/net"
  15. "v2ray.com/core/common/protocol"
  16. "v2ray.com/core/proxy"
  17. "v2ray.com/core/proxy/registry"
  18. "v2ray.com/core/transport/internet"
  19. "v2ray.com/core/transport/internet/udp"
  20. )
  21. type Server struct {
  22. packetDispatcher dispatcher.PacketDispatcher
  23. config *ServerConfig
  24. cipher Cipher
  25. cipherKey []byte
  26. meta *proxy.InboundHandlerMeta
  27. accepting bool
  28. tcpHub *internet.TCPHub
  29. udpHub *udp.UDPHub
  30. udpServer *udp.UDPServer
  31. }
  32. func NewServer(config *ServerConfig, space app.Space, meta *proxy.InboundHandlerMeta) (*Server, error) {
  33. if config.GetUser() == nil {
  34. return nil, protocol.ErrUserMissing
  35. }
  36. account := new(Account)
  37. if _, err := config.GetUser().GetTypedAccount(account); err != nil {
  38. return nil, err
  39. }
  40. cipher, err := account.GetCipher()
  41. if err != nil {
  42. return nil, err
  43. }
  44. s := &Server{
  45. config: config,
  46. meta: meta,
  47. cipher: cipher,
  48. cipherKey: account.GetCipherKey(),
  49. }
  50. space.InitializeApplication(func() error {
  51. if !space.HasApp(dispatcher.APP_ID) {
  52. return app.ErrMissingApplication
  53. }
  54. s.packetDispatcher = space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)
  55. return nil
  56. })
  57. return s, nil
  58. }
  59. func (this *Server) Port() v2net.Port {
  60. return this.meta.Port
  61. }
  62. func (this *Server) Close() {
  63. this.accepting = false
  64. // TODO: synchronization
  65. if this.tcpHub != nil {
  66. this.tcpHub.Close()
  67. this.tcpHub = nil
  68. }
  69. if this.udpHub != nil {
  70. this.udpHub.Close()
  71. this.udpHub = nil
  72. }
  73. }
  74. func (this *Server) Start() error {
  75. if this.accepting {
  76. return nil
  77. }
  78. tcpHub, err := internet.ListenTCP(this.meta.Address, this.meta.Port, this.handleConnection, this.meta.StreamSettings)
  79. if err != nil {
  80. log.Error("Shadowsocks: Failed to listen TCP on ", this.meta.Address, ":", this.meta.Port, ": ", err)
  81. return err
  82. }
  83. this.tcpHub = tcpHub
  84. if this.config.UdpEnabled {
  85. this.udpServer = udp.NewUDPServer(this.meta, this.packetDispatcher)
  86. udpHub, err := udp.ListenUDP(this.meta.Address, this.meta.Port, udp.ListenOption{Callback: this.handlerUDPPayload})
  87. if err != nil {
  88. log.Error("Shadowsocks: Failed to listen UDP on ", this.meta.Address, ":", this.meta.Port, ": ", err)
  89. return err
  90. }
  91. this.udpHub = udpHub
  92. }
  93. this.accepting = true
  94. return nil
  95. }
  96. func (this *Server) handlerUDPPayload(payload *alloc.Buffer, session *proxy.SessionInfo) {
  97. defer payload.Release()
  98. source := session.Source
  99. ivLen := this.cipher.IVSize()
  100. iv := payload.Value[:ivLen]
  101. payload.SliceFrom(ivLen)
  102. stream, err := this.cipher.NewDecodingStream(this.cipherKey, iv)
  103. if err != nil {
  104. log.Error("Shadowsocks: Failed to create decoding stream: ", err)
  105. return
  106. }
  107. reader := crypto.NewCryptionReader(stream, payload)
  108. request, err := ReadRequest(reader, NewAuthenticator(HeaderKeyGenerator(this.cipherKey, iv)), true)
  109. if err != nil {
  110. if err != io.EOF {
  111. log.Access(source, "", log.AccessRejected, err)
  112. log.Warning("Shadowsocks: Invalid request from ", source, ": ", err)
  113. }
  114. return
  115. }
  116. //defer request.Release()
  117. dest := v2net.UDPDestination(request.Address, request.Port)
  118. log.Access(source, dest, log.AccessAccepted, "")
  119. log.Info("Shadowsocks: Tunnelling request to ", dest)
  120. this.udpServer.Dispatch(&proxy.SessionInfo{Source: source, Destination: dest}, request.DetachUDPPayload(), func(destination v2net.Destination, payload *alloc.Buffer) {
  121. defer payload.Release()
  122. response := alloc.NewBuffer().Slice(0, ivLen)
  123. defer response.Release()
  124. rand.Read(response.Value)
  125. respIv := response.Value
  126. stream, err := this.cipher.NewEncodingStream(this.cipherKey, respIv)
  127. if err != nil {
  128. log.Error("Shadowsocks: Failed to create encoding stream: ", err)
  129. return
  130. }
  131. writer := crypto.NewCryptionWriter(stream, response)
  132. switch request.Address.Family() {
  133. case v2net.AddressFamilyIPv4:
  134. writer.Write([]byte{AddrTypeIPv4})
  135. writer.Write(request.Address.IP())
  136. case v2net.AddressFamilyIPv6:
  137. writer.Write([]byte{AddrTypeIPv6})
  138. writer.Write(request.Address.IP())
  139. case v2net.AddressFamilyDomain:
  140. writer.Write([]byte{AddrTypeDomain, byte(len(request.Address.Domain()))})
  141. writer.Write([]byte(request.Address.Domain()))
  142. }
  143. writer.Write(request.Port.Bytes(nil))
  144. writer.Write(payload.Value)
  145. if request.OTA {
  146. respAuth := NewAuthenticator(HeaderKeyGenerator(this.cipherKey, respIv))
  147. respAuth.Authenticate(response.Value, response.Value[ivLen:])
  148. }
  149. this.udpHub.WriteTo(response.Value, source)
  150. })
  151. }
  152. func (this *Server) handleConnection(conn internet.Connection) {
  153. defer conn.Close()
  154. buffer := alloc.NewSmallBuffer()
  155. defer buffer.Release()
  156. timedReader := v2net.NewTimeOutReader(16, conn)
  157. defer timedReader.Release()
  158. bufferedReader := v2io.NewBufferedReader(timedReader)
  159. defer bufferedReader.Release()
  160. ivLen := this.cipher.IVSize()
  161. _, err := io.ReadFull(bufferedReader, buffer.Value[:ivLen])
  162. if err != nil {
  163. if err != io.EOF {
  164. log.Access(conn.RemoteAddr(), "", log.AccessRejected, err)
  165. log.Warning("Shadowsocks: Failed to read IV: ", err)
  166. }
  167. return
  168. }
  169. iv := buffer.Value[:ivLen]
  170. stream, err := this.cipher.NewDecodingStream(this.cipherKey, iv)
  171. if err != nil {
  172. log.Error("Shadowsocks: Failed to create decoding stream: ", err)
  173. return
  174. }
  175. reader := crypto.NewCryptionReader(stream, bufferedReader)
  176. request, err := ReadRequest(reader, NewAuthenticator(HeaderKeyGenerator(this.cipherKey, iv)), false)
  177. if err != nil {
  178. log.Access(conn.RemoteAddr(), "", log.AccessRejected, err)
  179. log.Warning("Shadowsocks: Invalid request from ", conn.RemoteAddr(), ": ", err)
  180. return
  181. }
  182. defer request.Release()
  183. bufferedReader.SetCached(false)
  184. userSettings := this.config.GetUser().GetSettings()
  185. timedReader.SetTimeOut(userSettings.PayloadReadTimeout)
  186. dest := v2net.TCPDestination(request.Address, request.Port)
  187. log.Access(conn.RemoteAddr(), dest, log.AccessAccepted, "")
  188. log.Info("Shadowsocks: Tunnelling request to ", dest)
  189. ray := this.packetDispatcher.DispatchToOutbound(this.meta, &proxy.SessionInfo{
  190. Source: v2net.DestinationFromAddr(conn.RemoteAddr()),
  191. Destination: dest,
  192. })
  193. defer ray.InboundOutput().Release()
  194. var writeFinish sync.Mutex
  195. writeFinish.Lock()
  196. go func() {
  197. if payload, err := ray.InboundOutput().Read(); err == nil {
  198. payload.SliceBack(ivLen)
  199. rand.Read(payload.Value[:ivLen])
  200. stream, err := this.cipher.NewEncodingStream(this.cipherKey, payload.Value[:ivLen])
  201. if err != nil {
  202. log.Error("Shadowsocks: Failed to create encoding stream: ", err)
  203. return
  204. }
  205. stream.XORKeyStream(payload.Value[ivLen:], payload.Value[ivLen:])
  206. conn.Write(payload.Value)
  207. payload.Release()
  208. writer := crypto.NewCryptionWriter(stream, conn)
  209. v2writer := v2io.NewAdaptiveWriter(writer)
  210. v2io.Pipe(ray.InboundOutput(), v2writer)
  211. writer.Release()
  212. v2writer.Release()
  213. }
  214. writeFinish.Unlock()
  215. }()
  216. var payloadReader v2io.Reader
  217. if request.OTA {
  218. payloadAuth := NewAuthenticator(ChunkKeyGenerator(iv))
  219. payloadReader = NewChunkReader(reader, payloadAuth)
  220. } else {
  221. payloadReader = v2io.NewAdaptiveReader(reader)
  222. }
  223. v2io.Pipe(payloadReader, ray.InboundInput())
  224. ray.InboundInput().Close()
  225. payloadReader.Release()
  226. writeFinish.Lock()
  227. }
  228. type ServerFactory struct{}
  229. func (this *ServerFactory) StreamCapability() v2net.NetworkList {
  230. return v2net.NetworkList{
  231. Network: []v2net.Network{v2net.Network_RawTCP},
  232. }
  233. }
  234. func (this *ServerFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) {
  235. if !space.HasApp(dispatcher.APP_ID) {
  236. return nil, common.ErrBadConfiguration
  237. }
  238. return NewServer(rawConfig.(*ServerConfig), space, meta)
  239. }
  240. func init() {
  241. registry.MustRegisterInboundHandlerCreator("shadowsocks", new(ServerFactory))
  242. }