server.go 4.7 KB

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