dokodemo.go 5.8 KB

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