server.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package socks
  2. import (
  3. "context"
  4. "io"
  5. "runtime"
  6. "time"
  7. "v2ray.com/core/app"
  8. "v2ray.com/core/app/dispatcher"
  9. "v2ray.com/core/common"
  10. "v2ray.com/core/common/buf"
  11. "v2ray.com/core/common/bufio"
  12. "v2ray.com/core/common/errors"
  13. "v2ray.com/core/app/log"
  14. "v2ray.com/core/common/net"
  15. "v2ray.com/core/common/protocol"
  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. packetDispatcher dispatcher.Interface
  24. config *ServerConfig
  25. udpServer *udp.Dispatcher
  26. }
  27. // NewServer creates a new Server object.
  28. func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
  29. space := app.SpaceFromContext(ctx)
  30. if space == nil {
  31. return nil, errors.New("Socks|Server: No space in context.")
  32. }
  33. s := &Server{
  34. config: config,
  35. }
  36. space.OnInitialize(func() error {
  37. s.packetDispatcher = dispatcher.FromSpace(space)
  38. if s.packetDispatcher == nil {
  39. return errors.New("Socks|Server: Dispatcher is not found in the space.")
  40. }
  41. s.udpServer = udp.NewDispatcher(s.packetDispatcher)
  42. return nil
  43. })
  44. return s, nil
  45. }
  46. func (s *Server) Network() net.NetworkList {
  47. list := net.NetworkList{
  48. Network: []net.Network{net.Network_TCP},
  49. }
  50. if s.config.UdpEnabled {
  51. list.Network = append(list.Network, net.Network_UDP)
  52. }
  53. return list
  54. }
  55. func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection) error {
  56. conn.SetReusable(false)
  57. switch network {
  58. case net.Network_TCP:
  59. return s.processTCP(ctx, conn)
  60. case net.Network_UDP:
  61. return s.handleUDPPayload(ctx, conn)
  62. default:
  63. return errors.New("Socks|Server: Unknown network: ", network)
  64. }
  65. }
  66. func (s *Server) processTCP(ctx context.Context, conn internet.Connection) error {
  67. conn.SetReadDeadline(time.Now().Add(time.Second * 8))
  68. reader := bufio.NewReader(conn)
  69. inboundDest := proxy.InboundDestinationFromContext(ctx)
  70. session := &ServerSession{
  71. config: s.config,
  72. port: inboundDest.Port,
  73. }
  74. source := proxy.SourceFromContext(ctx)
  75. request, err := session.Handshake(reader, conn)
  76. if err != nil {
  77. log.Access(source, "", log.AccessRejected, err)
  78. log.Info("Socks|Server: Failed to read request: ", err)
  79. return err
  80. }
  81. conn.SetReadDeadline(time.Time{})
  82. if request.Command == protocol.RequestCommandTCP {
  83. dest := request.Destination()
  84. log.Info("Socks|Server: TCP Connect request to ", dest)
  85. log.Access(source, dest, log.AccessAccepted, "")
  86. ctx = proxy.ContextWithDestination(ctx, dest)
  87. return s.transport(ctx, reader, conn)
  88. }
  89. if request.Command == protocol.RequestCommandUDP {
  90. return s.handleUDP()
  91. }
  92. return nil
  93. }
  94. func (*Server) handleUDP() error {
  95. // The TCP connection closes after v method returns. We need to wait until
  96. // the client closes it.
  97. // TODO: get notified from UDP part
  98. <-time.After(5 * time.Minute)
  99. return nil
  100. }
  101. func (v *Server) transport(ctx context.Context, reader io.Reader, writer io.Writer) error {
  102. ctx, cancel := context.WithCancel(ctx)
  103. timeout := time.Second * time.Duration(v.config.Timeout)
  104. if timeout == 0 {
  105. timeout = time.Minute * 2
  106. }
  107. timer := signal.CancelAfterInactivity(ctx, cancel, timeout)
  108. ray := v.packetDispatcher.DispatchToOutbound(ctx)
  109. input := ray.InboundInput()
  110. output := ray.InboundOutput()
  111. requestDone := signal.ExecuteAsync(func() error {
  112. defer input.Close()
  113. v2reader := buf.NewReader(reader)
  114. if err := buf.PipeUntilEOF(timer, v2reader, input); err != nil {
  115. log.Info("Socks|Server: Failed to transport all TCP request: ", err)
  116. return err
  117. }
  118. return nil
  119. })
  120. responseDone := signal.ExecuteAsync(func() error {
  121. v2writer := buf.NewWriter(writer)
  122. if err := buf.PipeUntilEOF(timer, output, v2writer); err != nil {
  123. log.Info("Socks|Server: Failed to transport all TCP response: ", err)
  124. return err
  125. }
  126. return nil
  127. })
  128. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  129. log.Info("Socks|Server: Connection ends with ", err)
  130. input.CloseError()
  131. output.CloseError()
  132. return err
  133. }
  134. runtime.KeepAlive(timer)
  135. return nil
  136. }
  137. func (v *Server) handleUDPPayload(ctx context.Context, conn internet.Connection) error {
  138. source := proxy.SourceFromContext(ctx)
  139. log.Info("Socks|Server: Client UDP connection from ", source)
  140. reader := buf.NewReader(conn)
  141. for {
  142. payload, err := reader.Read()
  143. if err != nil {
  144. return err
  145. }
  146. request, data, err := DecodeUDPPacket(payload.Bytes())
  147. if err != nil {
  148. log.Info("Socks|Server: Failed to parse UDP request: ", err)
  149. continue
  150. }
  151. if len(data) == 0 {
  152. continue
  153. }
  154. log.Info("Socks: Send packet to ", request.Destination(), " with ", len(data), " bytes")
  155. log.Access(source, request.Destination, log.AccessAccepted, "")
  156. dataBuf := buf.NewSmall()
  157. dataBuf.Append(data)
  158. v.udpServer.Dispatch(ctx, request.Destination(), dataBuf, func(payload *buf.Buffer) {
  159. defer payload.Release()
  160. log.Info("Socks|Server: Writing back UDP response with ", payload.Len(), " bytes")
  161. udpMessage := EncodeUDPPacket(request, payload.Bytes())
  162. defer udpMessage.Release()
  163. conn.Write(udpMessage.Bytes())
  164. })
  165. }
  166. }
  167. func init() {
  168. common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  169. return NewServer(ctx, config.(*ServerConfig))
  170. }))
  171. }