dokodemo.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. package dokodemo
  2. //go:generate errorgen
  3. import (
  4. "context"
  5. "sync/atomic"
  6. "time"
  7. "v2ray.com/core"
  8. "v2ray.com/core/common"
  9. "v2ray.com/core/common/buf"
  10. "v2ray.com/core/common/net"
  11. "v2ray.com/core/common/session"
  12. "v2ray.com/core/common/signal"
  13. "v2ray.com/core/common/task"
  14. "v2ray.com/core/features/policy"
  15. "v2ray.com/core/features/routing"
  16. "v2ray.com/core/transport/internet"
  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. destinationOverridden := false
  71. if d.config.FollowRedirect {
  72. if outbound := session.OutboundFromContext(ctx); outbound != nil && outbound.Target.IsValid() {
  73. dest = outbound.Target
  74. destinationOverridden = true
  75. } else if handshake, ok := conn.(hasHandshakeAddress); ok {
  76. addr := handshake.HandshakeAddress()
  77. if addr != nil {
  78. dest.Address = addr
  79. destinationOverridden = true
  80. }
  81. }
  82. }
  83. if !dest.IsValid() || dest.Address == nil {
  84. return newError("unable to get destination")
  85. }
  86. plcy := d.policy()
  87. ctx, cancel := context.WithCancel(ctx)
  88. timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle)
  89. ctx = policy.ContextWithBufferPolicy(ctx, plcy.Buffer)
  90. link, err := dispatcher.Dispatch(ctx, dest)
  91. if err != nil {
  92. return newError("failed to dispatch request").Base(err)
  93. }
  94. requestCount := int32(1)
  95. requestDone := func() error {
  96. defer func() {
  97. if atomic.AddInt32(&requestCount, -1) == 0 {
  98. timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  99. }
  100. }()
  101. reader := buf.NewReader(conn)
  102. if err := buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)); err != nil {
  103. return newError("failed to transport request").Base(err)
  104. }
  105. return nil
  106. }
  107. tproxyRequest := func() error {
  108. return nil
  109. }
  110. var writer buf.Writer
  111. if network == net.Network_TCP {
  112. writer = buf.NewWriter(conn)
  113. } else {
  114. //if we are in TPROXY mode, use linux's udp forging functionality
  115. if !destinationOverridden {
  116. writer = &buf.SequentialWriter{Writer: conn}
  117. } else {
  118. sockopt := &internet.SocketConfig{
  119. Tproxy: internet.SocketConfig_TProxy,
  120. }
  121. if dest.Address.Family().IsIP() {
  122. sockopt.BindAddress = dest.Address.IP()
  123. sockopt.BindPort = uint32(dest.Port)
  124. }
  125. tConn, err := internet.DialSystem(ctx, net.DestinationFromAddr(conn.RemoteAddr()), sockopt)
  126. if err != nil {
  127. return err
  128. }
  129. defer tConn.Close()
  130. writer = &buf.SequentialWriter{Writer: tConn}
  131. tReader := buf.NewReader(tConn)
  132. requestCount++
  133. tproxyRequest = func() error {
  134. defer func() {
  135. if atomic.AddInt32(&requestCount, -1) == 0 {
  136. timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  137. }
  138. }()
  139. if err := buf.Copy(tReader, link.Writer, buf.UpdateActivity(timer)); err != nil {
  140. return newError("failed to transport request (TPROXY conn)").Base(err)
  141. }
  142. return nil
  143. }
  144. }
  145. }
  146. responseDone := func() error {
  147. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  148. if err := buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)); err != nil {
  149. return newError("failed to transport response").Base(err)
  150. }
  151. return nil
  152. }
  153. if err := task.Run(ctx, task.OnSuccess(requestDone, task.Close(link.Writer)), responseDone, tproxyRequest); err != nil {
  154. common.Interrupt(link.Reader)
  155. common.Interrupt(link.Writer)
  156. return newError("connection ends").Base(err)
  157. }
  158. return nil
  159. }