server.go 5.4 KB

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