server.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. return newError("failed to read request").Base(err)
  70. }
  71. conn.SetReadDeadline(time.Time{})
  72. if request.Command == protocol.RequestCommandTCP {
  73. dest := request.Destination()
  74. log.Trace(newError("TCP Connect request to ", dest))
  75. if source, ok := proxy.SourceFromContext(ctx); ok {
  76. log.Access(source, dest, log.AccessAccepted, "")
  77. }
  78. return s.transport(ctx, reader, conn, dest, dispatcher)
  79. }
  80. if request.Command == protocol.RequestCommandUDP {
  81. return s.handleUDP()
  82. }
  83. return nil
  84. }
  85. func (*Server) handleUDP() error {
  86. // The TCP connection closes after v method returns. We need to wait until
  87. // the client closes it.
  88. // TODO: get notified from UDP part
  89. time.Sleep(5 * time.Minute)
  90. return nil
  91. }
  92. func (v *Server) transport(ctx context.Context, reader io.Reader, writer io.Writer, dest net.Destination, dispatcher dispatcher.Interface) error {
  93. timeout := time.Second * time.Duration(v.config.Timeout)
  94. if timeout == 0 {
  95. timeout = time.Minute * 2
  96. }
  97. ctx, timer := signal.CancelAfterInactivity(ctx, timeout)
  98. ray, err := dispatcher.Dispatch(ctx, dest)
  99. if err != nil {
  100. return err
  101. }
  102. input := ray.InboundInput()
  103. output := ray.InboundOutput()
  104. requestDone := signal.ExecuteAsync(func() error {
  105. defer input.Close()
  106. v2reader := buf.NewReader(reader)
  107. if err := buf.Copy(v2reader, input, buf.UpdateActivity(timer)); err != nil {
  108. return newError("failed to transport all TCP request").Base(err)
  109. }
  110. return nil
  111. })
  112. responseDone := signal.ExecuteAsync(func() error {
  113. v2writer := buf.NewWriter(writer)
  114. if err := buf.Copy(output, v2writer, buf.UpdateActivity(timer)); err != nil {
  115. return newError("failed to transport all TCP response").Base(err)
  116. }
  117. return nil
  118. })
  119. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  120. input.CloseError()
  121. output.CloseError()
  122. return newError("connection ends").Base(err)
  123. }
  124. runtime.KeepAlive(timer)
  125. return nil
  126. }
  127. func (v *Server) handleUDPPayload(ctx context.Context, conn internet.Connection, dispatcher dispatcher.Interface) error {
  128. udpServer := udp.NewDispatcher(dispatcher)
  129. if source, ok := proxy.SourceFromContext(ctx); ok {
  130. log.Trace(newError("client UDP connection from ", source))
  131. }
  132. reader := buf.NewReader(conn)
  133. for {
  134. mpayload, err := reader.Read()
  135. if err != nil {
  136. return err
  137. }
  138. for _, payload := range mpayload {
  139. request, data, err := DecodeUDPPacket(payload.Bytes())
  140. if err != nil {
  141. log.Trace(newError("failed to parse UDP request").Base(err))
  142. continue
  143. }
  144. if len(data) == 0 {
  145. continue
  146. }
  147. log.Trace(newError("send packet to ", request.Destination(), " with ", len(data), " bytes").AtDebug())
  148. if source, ok := proxy.SourceFromContext(ctx); ok {
  149. log.Access(source, request.Destination, log.AccessAccepted, "")
  150. }
  151. dataBuf := buf.New()
  152. dataBuf.Append(data)
  153. udpServer.Dispatch(ctx, request.Destination(), dataBuf, func(payload *buf.Buffer) {
  154. defer payload.Release()
  155. log.Trace(newError("writing back UDP response with ", payload.Len(), " bytes").AtDebug())
  156. udpMessage := EncodeUDPPacket(request, payload.Bytes())
  157. defer udpMessage.Release()
  158. conn.Write(udpMessage.Bytes())
  159. })
  160. }
  161. }
  162. }
  163. func init() {
  164. common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  165. return NewServer(ctx, config.(*ServerConfig))
  166. }))
  167. }