server.go 6.8 KB

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