server.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. s.info = routingInfo{
  67. ctx: core.ToBackgroundDetachedContext(ctx),
  68. dispatcher: dispatcher,
  69. inboundTag: session.InboundFromContext(ctx),
  70. outboundTag: session.OutboundFromContext(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 && errors.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. newError("unexpected: dispatcher == nil").AtError().WriteToLog()
  105. return
  106. }
  107. defer conn.Close()
  108. ctx, cancel := context.WithCancel(core.ToBackgroundDetachedContext(s.info.ctx))
  109. plcy := s.policyManager.ForLevel(0)
  110. timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle)
  111. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  112. From: nullDestination,
  113. To: dest,
  114. Status: log.AccessAccepted,
  115. Reason: "",
  116. })
  117. if s.info.inboundTag != nil {
  118. ctx = session.ContextWithInbound(ctx, s.info.inboundTag)
  119. }
  120. if s.info.outboundTag != nil {
  121. ctx = session.ContextWithOutbound(ctx, s.info.outboundTag)
  122. }
  123. if s.info.contentTag != nil {
  124. ctx = session.ContextWithContent(ctx, s.info.contentTag)
  125. }
  126. link, err := s.info.dispatcher.Dispatch(ctx, dest)
  127. if err != nil {
  128. newError("dispatch connection").Base(err).AtError().WriteToLog()
  129. }
  130. defer cancel()
  131. requestDone := func() error {
  132. defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  133. if err := buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer)); err != nil {
  134. return newError("failed to transport all TCP request").Base(err)
  135. }
  136. return nil
  137. }
  138. responseDone := func() error {
  139. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  140. if err := buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer)); err != nil {
  141. return newError("failed to transport all TCP response").Base(err)
  142. }
  143. return nil
  144. }
  145. requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
  146. if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
  147. common.Interrupt(link.Reader)
  148. common.Interrupt(link.Writer)
  149. newError("connection ends").Base(err).AtDebug().WriteToLog()
  150. return
  151. }
  152. }