server.go 7.8 KB

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