server.go 9.0 KB

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