dokodemo.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. package dokodemo
  2. //go:generate errorgen
  3. import (
  4. "context"
  5. "time"
  6. "v2ray.com/core"
  7. "v2ray.com/core/common"
  8. "v2ray.com/core/common/buf"
  9. "v2ray.com/core/common/net"
  10. "v2ray.com/core/common/session"
  11. "v2ray.com/core/common/signal"
  12. "v2ray.com/core/common/task"
  13. "v2ray.com/core/features/policy"
  14. "v2ray.com/core/features/routing"
  15. "v2ray.com/core/transport/internet"
  16. "v2ray.com/core/transport/pipe"
  17. )
  18. func init() {
  19. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  20. d := new(DokodemoDoor)
  21. err := core.RequireFeatures(ctx, func(pm policy.Manager) error {
  22. return d.Init(config.(*Config), pm)
  23. })
  24. return d, err
  25. }))
  26. }
  27. type DokodemoDoor struct {
  28. policyManager policy.Manager
  29. config *Config
  30. address net.Address
  31. port net.Port
  32. }
  33. // Init initializes the DokodemoDoor instance with necessary parameters.
  34. func (d *DokodemoDoor) Init(config *Config, pm policy.Manager) error {
  35. if (config.NetworkList == nil || len(config.NetworkList.Network) == 0) && len(config.Networks) == 0 {
  36. return newError("no network specified")
  37. }
  38. d.config = config
  39. d.address = config.GetPredefinedAddress()
  40. d.port = net.Port(config.Port)
  41. d.policyManager = pm
  42. return nil
  43. }
  44. // Network implements proxy.Inbound.
  45. func (d *DokodemoDoor) Network() []net.Network {
  46. if len(d.config.Networks) > 0 {
  47. return d.config.Networks
  48. }
  49. return d.config.NetworkList.Network
  50. }
  51. func (d *DokodemoDoor) policy() policy.Session {
  52. config := d.config
  53. p := d.policyManager.ForLevel(config.UserLevel)
  54. if config.Timeout > 0 && config.UserLevel == 0 {
  55. p.Timeouts.ConnectionIdle = time.Duration(config.Timeout) * time.Second
  56. }
  57. return p
  58. }
  59. type hasHandshakeAddress interface {
  60. HandshakeAddress() net.Address
  61. }
  62. // Process implements proxy.Inbound.
  63. func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error {
  64. newError("processing connection from: ", conn.RemoteAddr()).AtDebug().WriteToLog(session.ExportIDToError(ctx))
  65. dest := net.Destination{
  66. Network: network,
  67. Address: d.address,
  68. Port: d.port,
  69. }
  70. if d.config.FollowRedirect {
  71. if outbound := session.OutboundFromContext(ctx); outbound != nil && outbound.Target.IsValid() {
  72. dest = outbound.Target
  73. } else if handshake, ok := conn.(hasHandshakeAddress); ok {
  74. addr := handshake.HandshakeAddress()
  75. if addr != nil {
  76. dest.Address = addr
  77. }
  78. }
  79. }
  80. if !dest.IsValid() || dest.Address == nil {
  81. return newError("unable to get destination")
  82. }
  83. plcy := d.policy()
  84. ctx, cancel := context.WithCancel(ctx)
  85. timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle)
  86. ctx = policy.ContextWithBufferPolicy(ctx, plcy.Buffer)
  87. link, err := dispatcher.Dispatch(ctx, dest)
  88. if err != nil {
  89. return newError("failed to dispatch request").Base(err)
  90. }
  91. requestDone := func() error {
  92. defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  93. reader := buf.NewReader(conn)
  94. if err := buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)); err != nil {
  95. return newError("failed to transport request").Base(err)
  96. }
  97. return nil
  98. }
  99. responseDone := func() error {
  100. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  101. var writer buf.Writer
  102. if network == net.Network_TCP {
  103. writer = buf.NewWriter(conn)
  104. } else {
  105. //if we are in TPROXY mode, use linux's udp forging functionality
  106. if !d.config.FollowRedirect {
  107. writer = &buf.SequentialWriter{Writer: conn}
  108. } else {
  109. tCtx := internet.ContextWithBindAddress(context.Background(), dest)
  110. tCtx = internet.ContextWithStreamSettings(tCtx, &internet.MemoryStreamConfig{
  111. ProtocolName: "udp",
  112. SocketSettings: &internet.SocketConfig{
  113. Tproxy: internet.SocketConfig_TProxy,
  114. },
  115. })
  116. tConn, err := internet.DialSystem(tCtx, net.DestinationFromAddr(conn.RemoteAddr()))
  117. if err != nil {
  118. return err
  119. }
  120. writer = &buf.SequentialWriter{Writer: tConn}
  121. }
  122. }
  123. if err := buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)); err != nil {
  124. return newError("failed to transport response").Base(err)
  125. }
  126. return nil
  127. }
  128. if err := task.Run(task.WithContext(ctx),
  129. task.Parallel(
  130. task.Single(requestDone, task.OnSuccess(task.Close(link.Writer))),
  131. responseDone))(); err != nil {
  132. pipe.CloseError(link.Reader)
  133. pipe.CloseError(link.Writer)
  134. return newError("connection ends").Base(err)
  135. }
  136. return nil
  137. }