server.go 8.8 KB

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