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
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. err = p.workerPool.Invoke(conn)
  47. switch {
  48. case err == nil:
  49. case errors.Is(err, ants.ErrPoolClosed):
  50. return nil
  51. case errors.Is(err, ants.ErrPoolOverload):
  52. p.eventStream.Send(p.ctx, EventConcurrencyLimited{})
  53. }
  54. }
  55. }
  56. func (p *Proxy) Shutdown() {
  57. p.ctxCancel()
  58. p.streamWaitGroup.Wait()
  59. p.workerPool.Release()
  60. }
  61. type antsLogger struct{}
  62. func (a antsLogger) Printf(msg string, args ...interface{}) {}
  63. func NewProxy(opts ProxyOpts) (*Proxy, error) {
  64. switch {
  65. case opts.Network == nil:
  66. return nil, ErrNetworkIsNotDefined
  67. case opts.AntiReplayCache == nil:
  68. return nil, ErrAntiReplayCacheIsNotDefined
  69. case opts.IPBlocklist == nil:
  70. return nil, ErrIPBlocklistIsNotDefined
  71. case opts.EventStream == nil:
  72. return nil, ErrEventStreamIsNotDefined
  73. case opts.Logger == nil:
  74. return nil, ErrLoggerIsNotDefined
  75. case !opts.Secret.Valid():
  76. return nil, ErrSecretInvalid
  77. }
  78. concurrency := opts.Concurrency
  79. if concurrency == 0 {
  80. concurrency = DefaultConcurrency
  81. }
  82. ctx, cancel := context.WithCancel(context.Background())
  83. proxy := &Proxy{
  84. ctx: ctx,
  85. ctxCancel: cancel,
  86. secret: opts.Secret,
  87. network: opts.Network,
  88. antiReplayCache: opts.AntiReplayCache,
  89. ipBlocklist: opts.IPBlocklist,
  90. eventStream: opts.EventStream,
  91. logger: opts.Logger.Named("proxy"),
  92. }
  93. pool, err := ants.NewPoolWithFunc(int(concurrency), func(arg interface{}) {
  94. proxy.ServeConn(arg.(net.Conn))
  95. }, ants.WithLogger(antsLogger{}))
  96. if err != nil {
  97. return nil, fmt.Errorf("cannot initialize a pool: %w", err)
  98. }
  99. proxy.workerPool = pool
  100. return proxy, nil
  101. }