server.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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, ok := proxy.InboundEntryPointFromContext(ctx)
  60. if !ok {
  61. return errors.New("Socks|Server: inbound entry point not specified.")
  62. }
  63. session := &ServerSession{
  64. config: s.config,
  65. port: inboundDest.Port,
  66. }
  67. request, err := session.Handshake(reader, conn)
  68. if err != nil {
  69. if source, ok := proxy.SourceFromContext(ctx); ok {
  70. log.Access(source, "", log.AccessRejected, err)
  71. }
  72. log.Info("Socks|Server: Failed to read request: ", err)
  73. return err
  74. }
  75. conn.SetReadDeadline(time.Time{})
  76. if request.Command == protocol.RequestCommandTCP {
  77. dest := request.Destination()
  78. log.Info("Socks|Server: TCP Connect request to ", dest)
  79. if source, ok := proxy.SourceFromContext(ctx); ok {
  80. log.Access(source, dest, log.AccessAccepted, "")
  81. }
  82. return s.transport(ctx, reader, conn, dest, dispatcher)
  83. }
  84. if request.Command == protocol.RequestCommandUDP {
  85. return s.handleUDP()
  86. }
  87. return nil
  88. }
  89. func (*Server) handleUDP() error {
  90. // The TCP connection closes after v method returns. We need to wait until
  91. // the client closes it.
  92. // TODO: get notified from UDP part
  93. <-time.After(5 * time.Minute)
  94. return nil
  95. }
  96. func (v *Server) transport(ctx context.Context, reader io.Reader, writer io.Writer, dest net.Destination, dispatcher dispatcher.Interface) error {
  97. ctx, cancel := context.WithCancel(ctx)
  98. timeout := time.Second * time.Duration(v.config.Timeout)
  99. if timeout == 0 {
  100. timeout = time.Minute * 2
  101. }
  102. timer := signal.CancelAfterInactivity(ctx, cancel, timeout)
  103. ray, err := dispatcher.Dispatch(ctx, dest)
  104. if err != nil {
  105. return err
  106. }
  107. input := ray.InboundInput()
  108. output := ray.InboundOutput()
  109. requestDone := signal.ExecuteAsync(func() error {
  110. defer input.Close()
  111. v2reader := buf.NewReader(reader)
  112. if err := buf.PipeUntilEOF(timer, v2reader, input); err != nil {
  113. log.Info("Socks|Server: Failed to transport all TCP request: ", err)
  114. return err
  115. }
  116. return nil
  117. })
  118. responseDone := signal.ExecuteAsync(func() error {
  119. v2writer := buf.NewWriter(writer)
  120. if err := buf.PipeUntilEOF(timer, output, v2writer); err != nil {
  121. log.Info("Socks|Server: Failed to transport all TCP response: ", err)
  122. return err
  123. }
  124. return nil
  125. })
  126. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  127. log.Info("Socks|Server: Connection ends with ", err)
  128. input.CloseError()
  129. output.CloseError()
  130. return err
  131. }
  132. runtime.KeepAlive(timer)
  133. return nil
  134. }
  135. func (v *Server) handleUDPPayload(ctx context.Context, conn internet.Connection, dispatcher dispatcher.Interface) error {
  136. udpServer := udp.NewDispatcher(dispatcher)
  137. if source, ok := proxy.SourceFromContext(ctx); ok {
  138. log.Info("Socks|Server: Client UDP connection from ", source)
  139. }
  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. if source, ok := proxy.SourceFromContext(ctx); ok {
  156. log.Access(source, request.Destination, log.AccessAccepted, "")
  157. }
  158. dataBuf := buf.NewSmall()
  159. dataBuf.Append(data)
  160. udpServer.Dispatch(ctx, request.Destination(), dataBuf, func(payload *buf.Buffer) {
  161. defer payload.Release()
  162. log.Info("Socks|Server: Writing back UDP response with ", payload.Len(), " bytes")
  163. udpMessage := EncodeUDPPacket(request, payload.Bytes())
  164. defer udpMessage.Release()
  165. conn.Write(udpMessage.Bytes())
  166. })
  167. }
  168. }
  169. func init() {
  170. common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  171. return NewServer(ctx, config.(*ServerConfig))
  172. }))
  173. }