server.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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/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. if config.Timeout > 0 {
  54. features.PrintDeprecatedFeatureWarning("Socks timeout")
  55. }
  56. if config.Timeout > 0 && config.UserLevel == 0 {
  57. p.Timeouts.ConnectionIdle = time.Duration(config.Timeout) * time.Second
  58. }
  59. return p
  60. }
  61. // Network implements proxy.Inbound.
  62. func (s *Server) Network() []net.Network {
  63. list := []net.Network{net.Network_TCP}
  64. if s.config.UdpEnabled {
  65. list = append(list, net.Network_UDP)
  66. }
  67. return list
  68. }
  69. // Process implements proxy.Inbound.
  70. func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Connection, dispatcher routing.Dispatcher) error {
  71. inbound := session.InboundFromContext(ctx)
  72. inbound.Name = "socks"
  73. inbound.CanSpliceCopy = 2
  74. inbound.User = &protocol.MemoryUser{
  75. Level: s.config.UserLevel,
  76. }
  77. switch network {
  78. case net.Network_TCP:
  79. firstbyte := make([]byte, 1)
  80. conn.Read(firstbyte)
  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. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  179. v2writer := buf.NewWriter(writer)
  180. if err := buf.Copy(link.Reader, v2writer, buf.UpdateActivity(timer)); err != nil {
  181. return errors.New("failed to transport all TCP response").Base(err)
  182. }
  183. return nil
  184. }
  185. requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
  186. if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
  187. common.Interrupt(link.Reader)
  188. common.Interrupt(link.Writer)
  189. return errors.New("connection ends").Base(err)
  190. }
  191. return nil
  192. }
  193. func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dispatcher routing.Dispatcher) error {
  194. if s.udpFilter != nil && !s.udpFilter.Check(conn.RemoteAddr()) {
  195. errors.LogDebug(ctx, "Unauthorized UDP access from ", conn.RemoteAddr().String())
  196. return nil
  197. }
  198. udpServer := udp.NewDispatcher(dispatcher, func(ctx context.Context, packet *udp_proto.Packet) {
  199. payload := packet.Payload
  200. errors.LogDebug(ctx, "writing back UDP response with ", payload.Len(), " bytes")
  201. request := protocol.RequestHeaderFromContext(ctx)
  202. if request == nil {
  203. return
  204. }
  205. if payload.UDP != nil {
  206. request = &protocol.RequestHeader{
  207. User: request.User,
  208. Address: payload.UDP.Address,
  209. Port: payload.UDP.Port,
  210. }
  211. }
  212. udpMessage, err := EncodeUDPPacket(request, payload.Bytes())
  213. payload.Release()
  214. defer udpMessage.Release()
  215. if err != nil {
  216. errors.LogWarningInner(ctx, err, "failed to write UDP response")
  217. }
  218. conn.Write(udpMessage.Bytes())
  219. })
  220. inbound := session.InboundFromContext(ctx)
  221. if inbound != nil && inbound.Source.IsValid() {
  222. errors.LogInfo(ctx, "client UDP connection from ", inbound.Source)
  223. }
  224. var dest *net.Destination
  225. reader := buf.NewPacketReader(conn)
  226. for {
  227. mpayload, err := reader.ReadMultiBuffer()
  228. if err != nil {
  229. return err
  230. }
  231. for _, payload := range mpayload {
  232. request, err := DecodeUDPPacket(payload)
  233. if err != nil {
  234. errors.LogInfoInner(ctx, err, "failed to parse UDP request")
  235. payload.Release()
  236. continue
  237. }
  238. if payload.IsEmpty() {
  239. payload.Release()
  240. continue
  241. }
  242. destination := request.Destination()
  243. currentPacketCtx := ctx
  244. errors.LogDebug(ctx, "send packet to ", destination, " with ", payload.Len(), " bytes")
  245. if inbound != nil && inbound.Source.IsValid() {
  246. currentPacketCtx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  247. From: inbound.Source,
  248. To: destination,
  249. Status: log.AccessAccepted,
  250. Reason: "",
  251. })
  252. }
  253. payload.UDP = &destination
  254. if !s.cone || dest == nil {
  255. dest = &destination
  256. }
  257. currentPacketCtx = protocol.ContextWithRequestHeader(currentPacketCtx, request)
  258. udpServer.Dispatch(currentPacketCtx, *dest, payload)
  259. }
  260. }
  261. }
  262. func init() {
  263. common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  264. return NewServer(ctx, config.(*ServerConfig))
  265. }))
  266. }