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