dokodemo.go 5.2 KB

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