server.go 5.1 KB

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