Highly-opinionated (ex-bullshit-free) MTPROTO proxy for Telegram. If you use v1.0 or upgrade broke you proxy, please read the chapter Version 2
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

proxy.go 2.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. package mtglib
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "sync"
  8. "time"
  9. "github.com/panjf2000/ants/v2"
  10. )
  11. type Proxy struct {
  12. ctx context.Context
  13. ctxCancel context.CancelFunc
  14. streamWaitGroup sync.WaitGroup
  15. workerPool *ants.PoolWithFunc
  16. secret Secret
  17. network Network
  18. antiReplayCache AntiReplayCache
  19. ipBlocklist IPBlocklist
  20. eventStream EventStream
  21. logger Logger
  22. }
  23. func (p *Proxy) ServeConn(conn net.Conn) {
  24. ctx := newStreamContext(p.ctx, p.logger, conn)
  25. defer ctx.Close()
  26. go func() {
  27. <-ctx.Done()
  28. ctx.Close()
  29. }()
  30. p.eventStream.Send(ctx, EventStart{
  31. CreatedAt: time.Now(),
  32. ConnID: ctx.connID,
  33. RemoteIP: ctx.ClientIP(),
  34. })
  35. ctx.logger.Info("Stream has been started")
  36. defer func() {
  37. p.eventStream.Send(ctx, EventFinish{
  38. CreatedAt: time.Now(),
  39. ConnID: ctx.connID,
  40. })
  41. ctx.logger.Info("Stream has been finished")
  42. }()
  43. }
  44. func (p *Proxy) Serve(listener net.Listener) error {
  45. for {
  46. conn, err := listener.Accept()
  47. if err != nil {
  48. return fmt.Errorf("cannot accept a new connection: %w", err)
  49. }
  50. if addr := conn.RemoteAddr().(*net.TCPAddr).IP; p.ipBlocklist.Contains(addr) {
  51. conn.Close()
  52. p.eventStream.Send(p.ctx, EventIPBlocklisted{
  53. CreatedAt: time.Now(),
  54. RemoteIP: addr,
  55. })
  56. continue
  57. }
  58. err = p.workerPool.Invoke(conn)
  59. switch {
  60. case err == nil:
  61. case errors.Is(err, ants.ErrPoolClosed):
  62. return nil
  63. case errors.Is(err, ants.ErrPoolOverload):
  64. p.eventStream.Send(p.ctx, EventConcurrencyLimited{})
  65. }
  66. }
  67. }
  68. func (p *Proxy) Shutdown() {
  69. p.ctxCancel()
  70. p.streamWaitGroup.Wait()
  71. p.workerPool.Release()
  72. }
  73. type antsLogger struct{}
  74. func (a antsLogger) Printf(msg string, args ...interface{}) {}
  75. func NewProxy(opts ProxyOpts) (*Proxy, error) {
  76. switch {
  77. case opts.Network == nil:
  78. return nil, ErrNetworkIsNotDefined
  79. case opts.AntiReplayCache == nil:
  80. return nil, ErrAntiReplayCacheIsNotDefined
  81. case opts.IPBlocklist == nil:
  82. return nil, ErrIPBlocklistIsNotDefined
  83. case opts.EventStream == nil:
  84. return nil, ErrEventStreamIsNotDefined
  85. case opts.Logger == nil:
  86. return nil, ErrLoggerIsNotDefined
  87. case !opts.Secret.Valid():
  88. return nil, ErrSecretInvalid
  89. }
  90. concurrency := opts.Concurrency
  91. if concurrency == 0 {
  92. concurrency = DefaultConcurrency
  93. }
  94. ctx, cancel := context.WithCancel(context.Background())
  95. proxy := &Proxy{
  96. ctx: ctx,
  97. ctxCancel: cancel,
  98. secret: opts.Secret,
  99. network: opts.Network,
  100. antiReplayCache: opts.AntiReplayCache,
  101. ipBlocklist: opts.IPBlocklist,
  102. eventStream: opts.EventStream,
  103. logger: opts.Logger.Named("proxy"),
  104. }
  105. pool, err := ants.NewPoolWithFunc(int(concurrency), func(arg interface{}) {
  106. proxy.ServeConn(arg.(net.Conn))
  107. }, ants.WithLogger(antsLogger{}))
  108. if err != nil {
  109. return nil, fmt.Errorf("cannot initialize a pool: %w", err)
  110. }
  111. proxy.workerPool = pool
  112. return proxy, nil
  113. }