dokodemo.go 4.1 KB

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