server.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. package socks
  2. import (
  3. "context"
  4. "io"
  5. "time"
  6. "v2ray.com/core"
  7. "v2ray.com/core/common"
  8. "v2ray.com/core/common/buf"
  9. "v2ray.com/core/common/log"
  10. "v2ray.com/core/common/net"
  11. "v2ray.com/core/common/protocol"
  12. "v2ray.com/core/common/session"
  13. "v2ray.com/core/common/signal"
  14. "v2ray.com/core/common/task"
  15. "v2ray.com/core/features"
  16. "v2ray.com/core/features/policy"
  17. "v2ray.com/core/features/routing"
  18. "v2ray.com/core/transport/internet"
  19. "v2ray.com/core/transport/internet/udp"
  20. "v2ray.com/core/transport/pipe"
  21. )
  22. // Server is a SOCKS 5 proxy server
  23. type Server struct {
  24. config *ServerConfig
  25. policyManager policy.Manager
  26. }
  27. // NewServer creates a new Server object.
  28. func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
  29. v := core.MustFromContext(ctx)
  30. s := &Server{
  31. config: config,
  32. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  33. }
  34. return s, nil
  35. }
  36. func (s *Server) policy() policy.Session {
  37. config := s.config
  38. p := s.policyManager.ForLevel(config.UserLevel)
  39. if config.Timeout > 0 {
  40. features.PrintDeprecatedFeatureWarning("Socks timeout")
  41. }
  42. if config.Timeout > 0 && config.UserLevel == 0 {
  43. p.Timeouts.ConnectionIdle = time.Duration(config.Timeout) * time.Second
  44. }
  45. return p
  46. }
  47. // Network implements proxy.Inbound.
  48. func (s *Server) Network() net.NetworkList {
  49. list := net.NetworkList{
  50. Network: []net.Network{net.Network_TCP},
  51. }
  52. if s.config.UdpEnabled {
  53. list.Network = append(list.Network, net.Network_UDP)
  54. }
  55. return list
  56. }
  57. // Process implements proxy.Inbound.
  58. func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error {
  59. switch network {
  60. case net.Network_TCP:
  61. return s.processTCP(ctx, conn, dispatcher)
  62. case net.Network_UDP:
  63. return s.handleUDPPayload(ctx, conn, dispatcher)
  64. default:
  65. return newError("unknown network: ", network)
  66. }
  67. }
  68. func (s *Server) processTCP(ctx context.Context, conn internet.Connection, dispatcher routing.Dispatcher) error {
  69. plcy := s.policy()
  70. if err := conn.SetReadDeadline(time.Now().Add(plcy.Timeouts.Handshake)); err != nil {
  71. newError("failed to set deadline").Base(err).WriteToLog(session.ExportIDToError(ctx))
  72. }
  73. inbound := session.InboundFromContext(ctx)
  74. if inbound == nil || !inbound.Gateway.IsValid() {
  75. return newError("inbound gateway not specified")
  76. }
  77. svrSession := &ServerSession{
  78. config: s.config,
  79. port: inbound.Gateway.Port,
  80. }
  81. reader := &buf.BufferedReader{Reader: buf.NewReader(conn)}
  82. request, err := svrSession.Handshake(reader, conn)
  83. if err != nil {
  84. if inbound != nil && inbound.Source.IsValid() {
  85. log.Record(&log.AccessMessage{
  86. From: inbound.Source,
  87. To: "",
  88. Status: log.AccessRejected,
  89. Reason: err,
  90. })
  91. }
  92. return newError("failed to read request").Base(err)
  93. }
  94. if err := conn.SetReadDeadline(time.Time{}); err != nil {
  95. newError("failed to clear deadline").Base(err).WriteToLog(session.ExportIDToError(ctx))
  96. }
  97. if request.Command == protocol.RequestCommandTCP {
  98. dest := request.Destination()
  99. newError("TCP Connect request to ", dest).WriteToLog(session.ExportIDToError(ctx))
  100. if inbound != nil && inbound.Source.IsValid() {
  101. log.Record(&log.AccessMessage{
  102. From: inbound.Source,
  103. To: dest,
  104. Status: log.AccessAccepted,
  105. Reason: "",
  106. })
  107. }
  108. return s.transport(ctx, reader, conn, dest, dispatcher)
  109. }
  110. if request.Command == protocol.RequestCommandUDP {
  111. return s.handleUDP(conn)
  112. }
  113. return nil
  114. }
  115. func (*Server) handleUDP(c io.Reader) error {
  116. // The TCP connection closes after this method returns. We need to wait until
  117. // the client closes it.
  118. return common.Error2(io.Copy(buf.DiscardBytes, c))
  119. }
  120. func (s *Server) transport(ctx context.Context, reader io.Reader, writer io.Writer, dest net.Destination, dispatcher routing.Dispatcher) error {
  121. ctx, cancel := context.WithCancel(ctx)
  122. timer := signal.CancelAfterInactivity(ctx, cancel, s.policy().Timeouts.ConnectionIdle)
  123. plcy := s.policy()
  124. ctx = policy.ContextWithBufferPolicy(ctx, plcy.Buffer)
  125. link, err := dispatcher.Dispatch(ctx, dest)
  126. if err != nil {
  127. return err
  128. }
  129. requestDone := func() error {
  130. defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  131. if err := buf.Copy(buf.NewReader(reader), link.Writer, buf.UpdateActivity(timer)); err != nil {
  132. return newError("failed to transport all TCP request").Base(err)
  133. }
  134. return nil
  135. }
  136. responseDone := func() error {
  137. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  138. v2writer := buf.NewWriter(writer)
  139. if err := buf.Copy(link.Reader, v2writer, buf.UpdateActivity(timer)); err != nil {
  140. return newError("failed to transport all TCP response").Base(err)
  141. }
  142. return nil
  143. }
  144. var requestDonePost = task.Single(requestDone, task.OnSuccess(task.Close(link.Writer)))
  145. if err := task.Run(task.WithContext(ctx), task.Parallel(requestDonePost, responseDone))(); err != nil {
  146. pipe.CloseError(link.Reader)
  147. pipe.CloseError(link.Writer)
  148. return newError("connection ends").Base(err)
  149. }
  150. return nil
  151. }
  152. func (s *Server) handleUDPPayload(ctx context.Context, conn internet.Connection, dispatcher routing.Dispatcher) error {
  153. udpServer := udp.NewDispatcher(dispatcher, func(ctx context.Context, payload *buf.Buffer) {
  154. newError("writing back UDP response with ", payload.Len(), " bytes").AtDebug().WriteToLog(session.ExportIDToError(ctx))
  155. request := protocol.RequestHeaderFromContext(ctx)
  156. if request == nil {
  157. return
  158. }
  159. udpMessage, err := EncodeUDPPacket(request, payload.Bytes())
  160. payload.Release()
  161. defer udpMessage.Release()
  162. if err != nil {
  163. newError("failed to write UDP response").AtWarning().Base(err).WriteToLog(session.ExportIDToError(ctx))
  164. }
  165. conn.Write(udpMessage.Bytes()) // nolint: errcheck
  166. })
  167. if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
  168. newError("client UDP connection from ", inbound.Source).WriteToLog(session.ExportIDToError(ctx))
  169. }
  170. reader := buf.NewReader(conn)
  171. for {
  172. mpayload, err := reader.ReadMultiBuffer()
  173. if err != nil {
  174. return err
  175. }
  176. for _, payload := range mpayload {
  177. request, err := DecodeUDPPacket(payload)
  178. if err != nil {
  179. newError("failed to parse UDP request").Base(err).WriteToLog(session.ExportIDToError(ctx))
  180. payload.Release()
  181. continue
  182. }
  183. if payload.IsEmpty() {
  184. payload.Release()
  185. continue
  186. }
  187. newError("send packet to ", request.Destination(), " with ", payload.Len(), " bytes").AtDebug().WriteToLog(session.ExportIDToError(ctx))
  188. if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
  189. log.Record(&log.AccessMessage{
  190. From: inbound.Source,
  191. To: request.Destination(),
  192. Status: log.AccessAccepted,
  193. Reason: "",
  194. })
  195. }
  196. ctx = protocol.ContextWithRequestHeader(ctx, request)
  197. udpServer.Dispatch(ctx, request.Destination(), payload)
  198. }
  199. }
  200. }
  201. func init() {
  202. common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  203. return NewServer(ctx, config.(*ServerConfig))
  204. }))
  205. }