server.go 7.9 KB

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