server.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. package socks
  2. import (
  3. "io"
  4. "sync"
  5. "time"
  6. "v2ray.com/core/app"
  7. "v2ray.com/core/app/dispatcher"
  8. "v2ray.com/core/common/buf"
  9. "v2ray.com/core/common/bufio"
  10. "v2ray.com/core/common/errors"
  11. "v2ray.com/core/common/log"
  12. v2net "v2ray.com/core/common/net"
  13. "v2ray.com/core/common/protocol"
  14. "v2ray.com/core/common/signal"
  15. "v2ray.com/core/proxy"
  16. "v2ray.com/core/transport/internet"
  17. "v2ray.com/core/transport/internet/udp"
  18. )
  19. // Server is a SOCKS 5 proxy server
  20. type Server struct {
  21. tcpMutex sync.RWMutex
  22. udpMutex sync.RWMutex
  23. accepting bool
  24. packetDispatcher dispatcher.PacketDispatcher
  25. config *ServerConfig
  26. tcpListener *internet.TCPHub
  27. udpHub *udp.Hub
  28. udpAddress v2net.Destination
  29. udpServer *udp.Server
  30. meta *proxy.InboundHandlerMeta
  31. }
  32. // NewServer creates a new Server object.
  33. func NewServer(config *ServerConfig, space app.Space, meta *proxy.InboundHandlerMeta) *Server {
  34. s := &Server{
  35. config: config,
  36. meta: meta,
  37. }
  38. space.OnInitialize(func() error {
  39. s.packetDispatcher = dispatcher.FromSpace(space)
  40. if s.packetDispatcher == nil {
  41. return errors.New("Socks|Server: Dispatcher is not found in the space.")
  42. }
  43. return nil
  44. })
  45. return s
  46. }
  47. // Port implements InboundHandler.Port().
  48. func (v *Server) Port() v2net.Port {
  49. return v.meta.Port
  50. }
  51. // Close implements InboundHandler.Close().
  52. func (v *Server) Close() {
  53. v.accepting = false
  54. if v.tcpListener != nil {
  55. v.tcpMutex.Lock()
  56. v.tcpListener.Close()
  57. v.tcpListener = nil
  58. v.tcpMutex.Unlock()
  59. }
  60. if v.udpHub != nil {
  61. v.udpMutex.Lock()
  62. v.udpHub.Close()
  63. v.udpHub = nil
  64. v.udpMutex.Unlock()
  65. }
  66. }
  67. // Start implements InboundHandler.Start().
  68. func (v *Server) Start() error {
  69. if v.accepting {
  70. return nil
  71. }
  72. listener, err := internet.ListenTCP(
  73. v.meta.Address,
  74. v.meta.Port,
  75. v.handleConnection,
  76. v.meta.StreamSettings)
  77. if err != nil {
  78. log.Error("Socks: failed to listen on ", v.meta.Address, ":", v.meta.Port, ": ", err)
  79. return err
  80. }
  81. v.accepting = true
  82. v.tcpMutex.Lock()
  83. v.tcpListener = listener
  84. v.tcpMutex.Unlock()
  85. if v.config.UdpEnabled {
  86. if err := v.listenUDP(); err != nil {
  87. return err
  88. }
  89. }
  90. return nil
  91. }
  92. func (v *Server) handleConnection(connection internet.Connection) {
  93. defer connection.Close()
  94. connection.SetReusable(false)
  95. timedReader := v2net.NewTimeOutReader(16 /* seconds, for handshake */, connection)
  96. reader := bufio.NewReader(timedReader)
  97. session := &ServerSession{
  98. config: v.config,
  99. meta: v.meta,
  100. }
  101. clientAddr := v2net.DestinationFromAddr(connection.RemoteAddr())
  102. request, err := session.Handshake(reader, connection)
  103. if err != nil {
  104. log.Access(clientAddr, "", log.AccessRejected, err)
  105. log.Info("Socks|Server: Failed to read request: ", err)
  106. return
  107. }
  108. if request.Command == protocol.RequestCommandTCP {
  109. dest := request.Destination()
  110. session := &proxy.SessionInfo{
  111. Source: clientAddr,
  112. Destination: dest,
  113. Inbound: v.meta,
  114. }
  115. log.Info("Socks|Server: TCP Connect request to ", dest)
  116. log.Access(clientAddr, dest, log.AccessAccepted, "")
  117. timedReader.SetTimeOut(v.config.Timeout)
  118. v.transport(reader, connection, session)
  119. return
  120. }
  121. if request.Command == protocol.RequestCommandUDP {
  122. v.handleUDP()
  123. return
  124. }
  125. }
  126. func (v *Server) handleUDP() {
  127. // The TCP connection closes after v method returns. We need to wait until
  128. // the client closes it.
  129. // TODO: get notified from UDP part
  130. <-time.After(5 * time.Minute)
  131. }
  132. func (v *Server) transport(reader io.Reader, writer io.Writer, session *proxy.SessionInfo) {
  133. ray := v.packetDispatcher.DispatchToOutbound(session)
  134. input := ray.InboundInput()
  135. output := ray.InboundOutput()
  136. requestDone := signal.ExecuteAsync(func() error {
  137. defer input.Close()
  138. v2reader := buf.NewReader(reader)
  139. if err := buf.PipeUntilEOF(v2reader, input); err != nil {
  140. log.Info("Socks|Server: Failed to transport all TCP request: ", err)
  141. return err
  142. }
  143. return nil
  144. })
  145. responseDone := signal.ExecuteAsync(func() error {
  146. v2writer := buf.NewWriter(writer)
  147. if err := buf.PipeUntilEOF(output, v2writer); err != nil {
  148. log.Info("Socks|Server: Failed to transport all TCP response: ", err)
  149. return err
  150. }
  151. return nil
  152. })
  153. if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil {
  154. log.Info("Socks|Server: Connection ends with ", err)
  155. input.CloseError()
  156. output.CloseError()
  157. }
  158. }
  159. type ServerFactory struct{}
  160. func (v *ServerFactory) StreamCapability() v2net.NetworkList {
  161. return v2net.NetworkList{
  162. Network: []v2net.Network{v2net.Network_TCP},
  163. }
  164. }
  165. func (v *ServerFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) {
  166. return NewServer(rawConfig.(*ServerConfig), space, meta), nil
  167. }