server.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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("no space in context").AtWarning().Path("Proxy", "Socks", "Server")
  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. switch network {
  46. case net.Network_TCP:
  47. return s.processTCP(ctx, conn, dispatcher)
  48. case net.Network_UDP:
  49. return s.handleUDPPayload(ctx, conn, dispatcher)
  50. default:
  51. return errors.New("unknown network: ", network).Path("Proxy", "Socks", "Server")
  52. }
  53. }
  54. func (s *Server) processTCP(ctx context.Context, conn internet.Connection, dispatcher dispatcher.Interface) error {
  55. conn.SetReadDeadline(time.Now().Add(time.Second * 8))
  56. reader := buf.NewBufferedReader(conn)
  57. inboundDest, ok := proxy.InboundEntryPointFromContext(ctx)
  58. if !ok {
  59. return errors.New("inbound entry point not specified").Path("Proxy", "Socks", "Server")
  60. }
  61. session := &ServerSession{
  62. config: s.config,
  63. port: inboundDest.Port,
  64. }
  65. request, err := session.Handshake(reader, conn)
  66. if err != nil {
  67. if source, ok := proxy.SourceFromContext(ctx); ok {
  68. log.Access(source, "", log.AccessRejected, err)
  69. }
  70. log.Trace(errors.New("failed to read request").Base(err).Path("Proxy", "Socks", "Server"))
  71. return err
  72. }
  73. conn.SetReadDeadline(time.Time{})
  74. if request.Command == protocol.RequestCommandTCP {
  75. dest := request.Destination()
  76. log.Trace(errors.New("TCP Connect request to ", dest).Path("Proxy", "Socks", "Server"))
  77. if source, ok := proxy.SourceFromContext(ctx); ok {
  78. log.Access(source, dest, log.AccessAccepted, "")
  79. }
  80. return s.transport(ctx, reader, conn, dest, dispatcher)
  81. }
  82. if request.Command == protocol.RequestCommandUDP {
  83. return s.handleUDP()
  84. }
  85. return nil
  86. }
  87. func (*Server) handleUDP() error {
  88. // The TCP connection closes after v method returns. We need to wait until
  89. // the client closes it.
  90. // TODO: get notified from UDP part
  91. <-time.After(5 * time.Minute)
  92. return nil
  93. }
  94. func (v *Server) transport(ctx context.Context, reader io.Reader, writer io.Writer, dest net.Destination, dispatcher dispatcher.Interface) error {
  95. timeout := time.Second * time.Duration(v.config.Timeout)
  96. if timeout == 0 {
  97. timeout = time.Minute * 2
  98. }
  99. ctx, timer := signal.CancelAfterInactivity(ctx, timeout)
  100. ray, err := dispatcher.Dispatch(ctx, dest)
  101. if err != nil {
  102. return err
  103. }
  104. input := ray.InboundInput()
  105. output := ray.InboundOutput()
  106. requestDone := signal.ExecuteAsync(func() error {
  107. defer input.Close()
  108. v2reader := buf.NewReader(reader)
  109. if err := buf.PipeUntilEOF(timer, v2reader, input); err != nil {
  110. return errors.New("failed to transport all TCP request").Base(err).Path("Proxy", "Socks", "Server")
  111. }
  112. return nil
  113. })
  114. responseDone := signal.ExecuteAsync(func() error {
  115. v2writer := buf.NewWriter(writer)
  116. if err := buf.PipeUntilEOF(timer, output, v2writer); err != nil {
  117. return errors.New("failed to transport all TCP response").Base(err).Path("Proxy", "Socks", "Server")
  118. }
  119. return nil
  120. })
  121. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  122. input.CloseError()
  123. output.CloseError()
  124. return errors.New("connection ends").Base(err).Path("Proxy", "Socks", "Server")
  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. if source, ok := proxy.SourceFromContext(ctx); ok {
  132. log.Trace(errors.New("client UDP connection from ", source).Path("Proxy", "Socks", "Server"))
  133. }
  134. reader := buf.NewReader(conn)
  135. for {
  136. payload, err := reader.Read()
  137. if err != nil {
  138. return err
  139. }
  140. request, data, err := DecodeUDPPacket(payload.Bytes())
  141. if err != nil {
  142. log.Trace(errors.New("failed to parse UDP request").Base(err).Path("Proxy", "Socks", "Server"))
  143. continue
  144. }
  145. if len(data) == 0 {
  146. continue
  147. }
  148. log.Trace(errors.New("send packet to ", request.Destination(), " with ", len(data), " bytes").Path("Proxy", "Socks", "Server").AtDebug())
  149. if source, ok := proxy.SourceFromContext(ctx); ok {
  150. log.Access(source, request.Destination, log.AccessAccepted, "")
  151. }
  152. dataBuf := buf.NewSmall()
  153. dataBuf.Append(data)
  154. udpServer.Dispatch(ctx, request.Destination(), dataBuf, func(payload *buf.Buffer) {
  155. defer payload.Release()
  156. log.Trace(errors.New("writing back UDP response with ", payload.Len(), " bytes").Path("Proxy", "Socks", "Server").AtDebug())
  157. udpMessage := EncodeUDPPacket(request, payload.Bytes())
  158. defer udpMessage.Release()
  159. conn.Write(udpMessage.Bytes())
  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. }