server.go 8.0 KB

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