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
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

proxy.go 4.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. package mtglib
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "sync"
  8. "time"
  9. "github.com/9seconds/mtg/v2/mtglib/internal/obfuscated2"
  10. "github.com/9seconds/mtg/v2/mtglib/internal/telegram"
  11. "github.com/panjf2000/ants/v2"
  12. )
  13. type Proxy struct {
  14. ctx context.Context
  15. ctxCancel context.CancelFunc
  16. streamWaitGroup sync.WaitGroup
  17. idleTimeout time.Duration
  18. workerPool *ants.PoolWithFunc
  19. telegram *telegram.Telegram
  20. secret Secret
  21. antiReplayCache AntiReplayCache
  22. ipBlocklist IPBlocklist
  23. eventStream EventStream
  24. logger Logger
  25. }
  26. func (p *Proxy) ServeConn(conn net.Conn) {
  27. ctx := newStreamContext(p.ctx, p.logger, conn)
  28. defer ctx.Close()
  29. go func() {
  30. <-ctx.Done()
  31. ctx.Close()
  32. }()
  33. p.eventStream.Send(ctx, EventStart{
  34. CreatedAt: time.Now(),
  35. ConnID: ctx.connID,
  36. RemoteIP: ctx.ClientIP(),
  37. })
  38. ctx.logger.Info("Stream has been started")
  39. defer func() {
  40. p.eventStream.Send(ctx, EventFinish{
  41. CreatedAt: time.Now(),
  42. ConnID: ctx.connID,
  43. })
  44. ctx.logger.Info("Stream has been finished")
  45. }()
  46. if err := p.doObfuscated2Handshake(ctx); err != nil {
  47. p.logger.InfoError("obfuscated2 handshake is failed", err)
  48. return
  49. }
  50. if err := p.doTelegramCall(ctx); err != nil {
  51. p.logger.WarningError("cannot dial to telegram", err)
  52. return
  53. }
  54. }
  55. func (p *Proxy) Serve(listener net.Listener) error {
  56. for {
  57. conn, err := listener.Accept()
  58. if err != nil {
  59. return fmt.Errorf("cannot accept a new connection: %w", err)
  60. }
  61. if addr := conn.RemoteAddr().(*net.TCPAddr).IP; p.ipBlocklist.Contains(addr) {
  62. conn.Close()
  63. p.eventStream.Send(p.ctx, EventIPBlocklisted{
  64. CreatedAt: time.Now(),
  65. RemoteIP: addr,
  66. })
  67. continue
  68. }
  69. err = p.workerPool.Invoke(conn)
  70. switch {
  71. case err == nil:
  72. case errors.Is(err, ants.ErrPoolClosed):
  73. return nil
  74. case errors.Is(err, ants.ErrPoolOverload):
  75. p.eventStream.Send(p.ctx, EventConcurrencyLimited{
  76. CreatedAt: time.Now(),
  77. })
  78. }
  79. }
  80. }
  81. func (p *Proxy) Shutdown() {
  82. p.ctxCancel()
  83. p.streamWaitGroup.Wait()
  84. p.workerPool.Release()
  85. }
  86. func (p *Proxy) doObfuscated2Handshake(ctx *streamContext) error {
  87. dc, encryptor, decryptor, err := obfuscated2.ClientHandshake(p.secret.Key[:], ctx.clientConn)
  88. if err != nil {
  89. return fmt.Errorf("cannot process client handshake: %w", err)
  90. }
  91. ctx.dc = dc
  92. ctx.logger = ctx.logger.BindInt("dc", dc)
  93. ctx.clientConn = connStandard{
  94. conn: obfuscated2.Conn{
  95. Conn: ctx.clientConn,
  96. Encryptor: encryptor,
  97. Decryptor: decryptor,
  98. },
  99. idleTimeout: p.idleTimeout,
  100. }
  101. return nil
  102. }
  103. func (p *Proxy) doTelegramCall(ctx *streamContext) error {
  104. conn, err := p.telegram.Dial(ctx, ctx.dc)
  105. if err != nil {
  106. return fmt.Errorf("cannot dial to Telegram: %w", err)
  107. }
  108. ctx.telegramConn = connEventTraffic{
  109. connStandard: connStandard{
  110. conn: conn,
  111. idleTimeout: p.idleTimeout,
  112. },
  113. connID: ctx.connID,
  114. stream: p.eventStream,
  115. ctx: ctx,
  116. }
  117. p.eventStream.Send(ctx, EventConnectedToDC{
  118. CreatedAt: time.Now(),
  119. ConnID: ctx.connID,
  120. RemoteIP: conn.RemoteAddr().(*net.TCPAddr).IP,
  121. DC: ctx.dc,
  122. })
  123. return nil
  124. }
  125. func NewProxy(opts ProxyOpts) (*Proxy, error) { // nolint: cyclop
  126. switch {
  127. case opts.Network == nil:
  128. return nil, ErrNetworkIsNotDefined
  129. case opts.AntiReplayCache == nil:
  130. return nil, ErrAntiReplayCacheIsNotDefined
  131. case opts.IPBlocklist == nil:
  132. return nil, ErrIPBlocklistIsNotDefined
  133. case opts.EventStream == nil:
  134. return nil, ErrEventStreamIsNotDefined
  135. case opts.Logger == nil:
  136. return nil, ErrLoggerIsNotDefined
  137. case !opts.Secret.Valid():
  138. return nil, ErrSecretInvalid
  139. }
  140. tg, err := telegram.New(opts.Network, opts.PreferIP)
  141. if err != nil {
  142. return nil, fmt.Errorf("cannot build telegram dialer: %w", err)
  143. }
  144. concurrency := opts.Concurrency
  145. if concurrency == 0 {
  146. concurrency = DefaultConcurrency
  147. }
  148. idleTimeout := opts.IdleTimeout
  149. if idleTimeout < 1 {
  150. idleTimeout = DefaultIdleTimeout
  151. }
  152. ctx, cancel := context.WithCancel(context.Background())
  153. proxy := &Proxy{
  154. ctx: ctx,
  155. ctxCancel: cancel,
  156. secret: opts.Secret,
  157. antiReplayCache: opts.AntiReplayCache,
  158. ipBlocklist: opts.IPBlocklist,
  159. eventStream: opts.EventStream,
  160. logger: opts.Logger.Named("proxy"),
  161. idleTimeout: idleTimeout,
  162. telegram: tg,
  163. }
  164. pool, err := ants.NewPoolWithFunc(int(concurrency), func(arg interface{}) {
  165. proxy.ServeConn(arg.(net.Conn))
  166. }, ants.WithLogger(opts.Logger.Named("ants")))
  167. if err != nil {
  168. return nil, fmt.Errorf("cannot initialize a pool: %w", err)
  169. }
  170. proxy.workerPool = pool
  171. return proxy, nil
  172. }