server.go 7.5 KB

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