server.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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"
  9. "v2ray.com/core/common/buf"
  10. "v2ray.com/core/common/bufio"
  11. "v2ray.com/core/common/errors"
  12. "v2ray.com/core/common/log"
  13. v2net "v2ray.com/core/common/net"
  14. proto "v2ray.com/core/common/protocol"
  15. "v2ray.com/core/common/serial"
  16. "v2ray.com/core/common/signal"
  17. "v2ray.com/core/proxy"
  18. "v2ray.com/core/transport/internet"
  19. "v2ray.com/core/transport/internet/udp"
  20. )
  21. // Server is a SOCKS 5 proxy server
  22. type Server struct {
  23. tcpMutex sync.RWMutex
  24. udpMutex sync.RWMutex
  25. accepting bool
  26. packetDispatcher dispatcher.PacketDispatcher
  27. config *ServerConfig
  28. tcpListener *internet.TCPHub
  29. udpHub *udp.Hub
  30. udpAddress v2net.Destination
  31. udpServer *udp.Server
  32. meta *proxy.InboundHandlerMeta
  33. }
  34. // NewServer creates a new Server object.
  35. func NewServer(config *ServerConfig, space app.Space, meta *proxy.InboundHandlerMeta) *Server {
  36. s := &Server{
  37. config: config,
  38. meta: meta,
  39. }
  40. space.InitializeApplication(func() error {
  41. if !space.HasApp(dispatcher.APP_ID) {
  42. return errors.New("Socks|Server: Dispatcher is not found in the space.")
  43. }
  44. s.packetDispatcher = space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)
  45. return nil
  46. })
  47. return s
  48. }
  49. // Port implements InboundHandler.Port().
  50. func (v *Server) Port() v2net.Port {
  51. return v.meta.Port
  52. }
  53. // Close implements InboundHandler.Close().
  54. func (v *Server) Close() {
  55. v.accepting = false
  56. if v.tcpListener != nil {
  57. v.tcpMutex.Lock()
  58. v.tcpListener.Close()
  59. v.tcpListener = nil
  60. v.tcpMutex.Unlock()
  61. }
  62. if v.udpHub != nil {
  63. v.udpMutex.Lock()
  64. v.udpHub.Close()
  65. v.udpHub = nil
  66. v.udpMutex.Unlock()
  67. }
  68. }
  69. // Start implements InboundHandler.Start().
  70. func (v *Server) Start() error {
  71. if v.accepting {
  72. return nil
  73. }
  74. listener, err := internet.ListenTCP(
  75. v.meta.Address,
  76. v.meta.Port,
  77. v.handleConnection,
  78. v.meta.StreamSettings)
  79. if err != nil {
  80. log.Error("Socks: failed to listen on ", v.meta.Address, ":", v.meta.Port, ": ", err)
  81. return err
  82. }
  83. v.accepting = true
  84. v.tcpMutex.Lock()
  85. v.tcpListener = listener
  86. v.tcpMutex.Unlock()
  87. if v.config.UdpEnabled {
  88. v.listenUDP()
  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(v.config.Timeout, 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 == proto.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. v.transport(reader, connection, session)
  118. return
  119. }
  120. if request.Command == proto.RequestCommandUDP {
  121. v.handleUDP()
  122. return
  123. }
  124. }
  125. func (v *Server) handleUDP() error {
  126. // The TCP connection closes after v method returns. We need to wait until
  127. // the client closes it.
  128. // TODO: get notified from UDP part
  129. <-time.After(5 * time.Minute)
  130. return nil
  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. defer output.ForceClose()
  147. v2writer := buf.NewWriter(writer)
  148. if err := buf.PipeUntilEOF(output, v2writer); err != nil {
  149. log.Info("Socks|Server: Failed to transport all TCP response: ", err)
  150. return err
  151. }
  152. return nil
  153. })
  154. if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil {
  155. log.Info("Socks|Server: Connection ends with ", err)
  156. }
  157. }
  158. type ServerFactory struct{}
  159. func (v *ServerFactory) StreamCapability() v2net.NetworkList {
  160. return v2net.NetworkList{
  161. Network: []v2net.Network{v2net.Network_TCP},
  162. }
  163. }
  164. func (v *ServerFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) {
  165. return NewServer(rawConfig.(*ServerConfig), space, meta), nil
  166. }
  167. func init() {
  168. common.Must(proxy.RegisterInboundHandlerCreator(serial.GetMessageType(new(ServerConfig)), new(ServerFactory)))
  169. }