handler.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. package tun
  2. import (
  3. "context"
  4. "github.com/xtls/xray-core/common"
  5. "github.com/xtls/xray-core/common/buf"
  6. c "github.com/xtls/xray-core/common/ctx"
  7. "github.com/xtls/xray-core/common/errors"
  8. "github.com/xtls/xray-core/common/log"
  9. "github.com/xtls/xray-core/common/net"
  10. "github.com/xtls/xray-core/common/protocol"
  11. "github.com/xtls/xray-core/common/session"
  12. "github.com/xtls/xray-core/core"
  13. "github.com/xtls/xray-core/features/policy"
  14. "github.com/xtls/xray-core/features/routing"
  15. "github.com/xtls/xray-core/transport"
  16. "github.com/xtls/xray-core/transport/internet/stat"
  17. )
  18. // Handler is managing object that tie together tun interface, ip stack and dispatch connections to the routing
  19. type Handler struct {
  20. ctx context.Context
  21. config *Config
  22. stack Stack
  23. policyManager policy.Manager
  24. dispatcher routing.Dispatcher
  25. tag string
  26. sniffingRequest session.SniffingRequest
  27. }
  28. // ConnectionHandler interface with the only method that stack is going to push new connections to
  29. type ConnectionHandler interface {
  30. HandleConnection(conn net.Conn, destination net.Destination)
  31. }
  32. // Handler implements ConnectionHandler
  33. var _ ConnectionHandler = (*Handler)(nil)
  34. func (t *Handler) policy() policy.Session {
  35. p := t.policyManager.ForLevel(t.config.UserLevel)
  36. return p
  37. }
  38. // Init the Handler instance with necessary parameters
  39. func (t *Handler) Init(ctx context.Context, pm policy.Manager, dispatcher routing.Dispatcher) error {
  40. var err error
  41. // Retrieve tag and sniffing config from context (set by AlwaysOnInboundHandler)
  42. if inbound := session.InboundFromContext(ctx); inbound != nil {
  43. t.tag = inbound.Tag
  44. }
  45. if content := session.ContentFromContext(ctx); content != nil {
  46. t.sniffingRequest = content.SniffingRequest
  47. }
  48. t.ctx = core.ToBackgroundDetachedContext(ctx)
  49. t.policyManager = pm
  50. t.dispatcher = dispatcher
  51. tunName := t.config.Name
  52. tunOptions := TunOptions{
  53. Name: tunName,
  54. MTU: t.config.MTU,
  55. }
  56. tunInterface, err := NewTun(tunOptions)
  57. if err != nil {
  58. return err
  59. }
  60. errors.LogInfo(t.ctx, tunName, " created")
  61. tunStackOptions := StackOptions{
  62. Tun: tunInterface,
  63. IdleTimeout: pm.ForLevel(t.config.UserLevel).Timeouts.ConnectionIdle,
  64. }
  65. tunStack, err := NewStack(t.ctx, tunStackOptions, t)
  66. if err != nil {
  67. _ = tunInterface.Close()
  68. return err
  69. }
  70. err = tunStack.Start()
  71. if err != nil {
  72. _ = tunStack.Close()
  73. _ = tunInterface.Close()
  74. return err
  75. }
  76. err = tunInterface.Start()
  77. if err != nil {
  78. _ = tunStack.Close()
  79. _ = tunInterface.Close()
  80. return err
  81. }
  82. t.stack = tunStack
  83. errors.LogInfo(t.ctx, tunName, " up")
  84. return nil
  85. }
  86. // HandleConnection pass the connection coming from the ip stack to the routing dispatcher
  87. func (t *Handler) HandleConnection(conn net.Conn, destination net.Destination) {
  88. // when handling is done with any outcome, always signal back to the incoming connection
  89. // to close, send completion packets back to the network, and cleanup
  90. defer conn.Close()
  91. sid := session.NewID()
  92. ctx := c.ContextWithID(t.ctx, sid)
  93. source := net.DestinationFromAddr(conn.RemoteAddr())
  94. inbound := session.Inbound{
  95. Name: "tun",
  96. Tag: t.tag,
  97. CanSpliceCopy: 3,
  98. Source: source,
  99. User: &protocol.MemoryUser{
  100. Level: t.config.UserLevel,
  101. },
  102. }
  103. ctx = session.ContextWithInbound(ctx, &inbound)
  104. ctx = session.ContextWithContent(ctx, &session.Content{
  105. SniffingRequest: t.sniffingRequest,
  106. })
  107. ctx = session.SubContextFromMuxInbound(ctx)
  108. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  109. From: inbound.Source,
  110. To: destination,
  111. Status: log.AccessAccepted,
  112. Reason: "",
  113. })
  114. errors.LogInfo(ctx, "processing from ", source, " to ", destination)
  115. link := &transport.Link{
  116. Reader: &buf.TimeoutWrapperReader{Reader: buf.NewReader(conn)},
  117. Writer: buf.NewWriter(conn),
  118. }
  119. if err := t.dispatcher.DispatchLink(ctx, destination, link); err != nil {
  120. errors.LogError(ctx, errors.New("connection closed").Base(err))
  121. }
  122. }
  123. // Network implements proxy.Inbound
  124. // and exists only to comply to proxy interface, declaring it doesn't listen on any network,
  125. // making the process not open any port for this inbound (input will be network interface)
  126. func (t *Handler) Network() []net.Network {
  127. return []net.Network{}
  128. }
  129. // Process implements proxy.Inbound
  130. // and exists only to comply to proxy interface, which should never get any inputs due to no listening ports
  131. func (t *Handler) Process(ctx context.Context, network net.Network, conn stat.Connection, dispatcher routing.Dispatcher) error {
  132. return nil
  133. }
  134. func init() {
  135. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  136. t := &Handler{config: config.(*Config)}
  137. err := core.RequireFeatures(ctx, func(pm policy.Manager, dispatcher routing.Dispatcher) error {
  138. return t.Init(ctx, pm, dispatcher)
  139. })
  140. return t, err
  141. }))
  142. }