server.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. package wireguard
  2. import (
  3. "context"
  4. goerrors "errors"
  5. "io"
  6. "github.com/xtls/xray-core/common"
  7. "github.com/xtls/xray-core/common/buf"
  8. c "github.com/xtls/xray-core/common/ctx"
  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/session"
  13. "github.com/xtls/xray-core/common/signal"
  14. "github.com/xtls/xray-core/common/task"
  15. "github.com/xtls/xray-core/core"
  16. "github.com/xtls/xray-core/features/dns"
  17. "github.com/xtls/xray-core/features/policy"
  18. "github.com/xtls/xray-core/features/routing"
  19. "github.com/xtls/xray-core/transport/internet/stat"
  20. )
  21. var nullDestination = net.TCPDestination(net.AnyIP, 0)
  22. type Server struct {
  23. bindServer *netBindServer
  24. info routingInfo
  25. policyManager policy.Manager
  26. }
  27. type routingInfo struct {
  28. ctx context.Context
  29. dispatcher routing.Dispatcher
  30. inboundTag *session.Inbound
  31. contentTag *session.Content
  32. }
  33. func NewServer(ctx context.Context, conf *DeviceConfig) (*Server, error) {
  34. v := core.MustFromContext(ctx)
  35. endpoints, hasIPv4, hasIPv6, err := parseEndpoints(conf)
  36. if err != nil {
  37. return nil, err
  38. }
  39. server := &Server{
  40. bindServer: &netBindServer{
  41. netBind: netBind{
  42. dns: v.GetFeature(dns.ClientType()).(dns.Client),
  43. dnsOption: dns.IPOption{
  44. IPv4Enable: hasIPv4,
  45. IPv6Enable: hasIPv6,
  46. },
  47. },
  48. },
  49. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  50. }
  51. tun, err := conf.createTun()(endpoints, int(conf.Mtu), server.forwardConnection)
  52. if err != nil {
  53. return nil, err
  54. }
  55. if err = tun.BuildDevice(createIPCRequest(conf), server.bindServer); err != nil {
  56. _ = tun.Close()
  57. return nil, err
  58. }
  59. return server, nil
  60. }
  61. // Network implements proxy.Inbound.
  62. func (*Server) Network() []net.Network {
  63. return []net.Network{net.Network_UDP}
  64. }
  65. // Process implements proxy.Inbound.
  66. func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Connection, dispatcher routing.Dispatcher) error {
  67. s.info = routingInfo{
  68. ctx: ctx,
  69. dispatcher: dispatcher,
  70. inboundTag: session.InboundFromContext(ctx),
  71. contentTag: session.ContentFromContext(ctx),
  72. }
  73. ep, err := s.bindServer.ParseEndpoint(conn.RemoteAddr().String())
  74. if err != nil {
  75. return err
  76. }
  77. nep := ep.(*netEndpoint)
  78. nep.conn = conn
  79. reader := buf.NewPacketReader(conn)
  80. for {
  81. mpayload, err := reader.ReadMultiBuffer()
  82. if err != nil {
  83. return err
  84. }
  85. for _, payload := range mpayload {
  86. v, ok := <-s.bindServer.readQueue
  87. if !ok {
  88. return nil
  89. }
  90. i, err := payload.Read(v.buff)
  91. v.bytes = i
  92. v.endpoint = nep
  93. v.err = err
  94. v.waiter.Done()
  95. if err != nil && goerrors.Is(err, io.EOF) {
  96. nep.conn = nil
  97. return nil
  98. }
  99. }
  100. }
  101. }
  102. func (s *Server) forwardConnection(dest net.Destination, conn net.Conn) {
  103. if s.info.dispatcher == nil {
  104. errors.LogError(s.info.ctx, "unexpected: dispatcher == nil")
  105. return
  106. }
  107. defer conn.Close()
  108. ctx, cancel := context.WithCancel(core.ToBackgroundDetachedContext(s.info.ctx))
  109. sid := session.NewID()
  110. ctx = c.ContextWithID(ctx, sid)
  111. inbound := session.Inbound{} // since promiscuousModeHandler mixed-up context, we shallow copy inbound (tag) and content (configs)
  112. if s.info.inboundTag != nil {
  113. inbound = *s.info.inboundTag
  114. }
  115. inbound.Name = "wireguard"
  116. inbound.CanSpliceCopy = 3
  117. // overwrite the source to use the tun address for each sub context.
  118. // Since gvisor.ForwarderRequest doesn't provide any info to associate the sub-context with the Parent context
  119. // Currently we have no way to link to the original source address
  120. inbound.Source = net.DestinationFromAddr(conn.RemoteAddr())
  121. ctx = session.ContextWithInbound(ctx, &inbound)
  122. if s.info.contentTag != nil {
  123. ctx = session.ContextWithContent(ctx, s.info.contentTag)
  124. }
  125. ctx = session.SubContextFromMuxInbound(ctx)
  126. plcy := s.policyManager.ForLevel(0)
  127. timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle)
  128. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  129. From: nullDestination,
  130. To: dest,
  131. Status: log.AccessAccepted,
  132. Reason: "",
  133. })
  134. link, err := s.info.dispatcher.Dispatch(ctx, dest)
  135. if err != nil {
  136. errors.LogErrorInner(ctx, err, "dispatch connection")
  137. }
  138. defer cancel()
  139. requestDone := func() error {
  140. defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  141. if err := buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer)); err != nil {
  142. return errors.New("failed to transport all TCP request").Base(err)
  143. }
  144. return nil
  145. }
  146. responseDone := func() error {
  147. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  148. if err := buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer)); err != nil {
  149. return errors.New("failed to transport all TCP response").Base(err)
  150. }
  151. return nil
  152. }
  153. requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
  154. if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
  155. common.Interrupt(link.Reader)
  156. common.Interrupt(link.Writer)
  157. errors.LogDebugInner(ctx, err, "connection ends")
  158. return
  159. }
  160. }