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
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

proxy.go 2.8KB

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