server.go 8.0 KB

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