dokodemo.go 5.0 KB

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