server.go 8.5 KB

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