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.

proxy.go 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package cli
  2. import (
  3. "net"
  4. "os"
  5. "time"
  6. "go.uber.org/zap"
  7. "go.uber.org/zap/zapcore"
  8. "github.com/9seconds/mtg/antireplay"
  9. "github.com/9seconds/mtg/config"
  10. "github.com/9seconds/mtg/ntp"
  11. "github.com/9seconds/mtg/obfuscated2"
  12. "github.com/9seconds/mtg/proxy"
  13. "github.com/9seconds/mtg/stats"
  14. "github.com/9seconds/mtg/telegram"
  15. "github.com/9seconds/mtg/utils"
  16. )
  17. func Proxy() error {
  18. ctx := utils.GetSignalContext()
  19. atom := zap.NewAtomicLevel()
  20. switch {
  21. case config.C.Debug:
  22. atom.SetLevel(zapcore.DebugLevel)
  23. case config.C.Verbose:
  24. atom.SetLevel(zapcore.InfoLevel)
  25. default:
  26. atom.SetLevel(zapcore.ErrorLevel)
  27. }
  28. encoderCfg := zap.NewProductionEncoderConfig()
  29. logger := zap.New(zapcore.NewCore(
  30. zapcore.NewJSONEncoder(encoderCfg),
  31. zapcore.Lock(os.Stderr),
  32. atom,
  33. ))
  34. zap.ReplaceGlobals(logger)
  35. defer logger.Sync() // nolint: errcheck
  36. if err := config.InitPublicAddress(ctx); err != nil {
  37. Fatal(err)
  38. }
  39. zap.S().Debugw("Configuration", "config", config.Printable())
  40. if len(config.C.AdTag) > 0 {
  41. zap.S().Infow("Use middle proxy connection to Telegram")
  42. diff, err := ntp.Fetch()
  43. if err != nil {
  44. Fatal("Cannot fetch time data from NTP")
  45. }
  46. if diff > time.Second {
  47. Fatal("Your local time is skewed and drift is bigger than a second. Please sync your time.")
  48. }
  49. go ntp.AutoUpdate()
  50. } else {
  51. zap.S().Infow("Use direct connection to Telegram")
  52. }
  53. PrintJSONStdout(config.GetURLs())
  54. antireplay.Init()
  55. if err := stats.Init(ctx); err != nil {
  56. Fatal(err)
  57. }
  58. telegram.MiddleInit()
  59. proxyListener, err := net.Listen("tcp", config.C.Bind.String())
  60. if err != nil {
  61. Fatal(err)
  62. }
  63. go func() {
  64. <-ctx.Done()
  65. proxyListener.Close()
  66. }()
  67. app := &proxy.Proxy{
  68. Logger: zap.S().Named("proxy"),
  69. Context: ctx,
  70. ClientProtocolMaker: obfuscated2.MakeClientProtocol,
  71. }
  72. // if len(config.C.AdTag) == 0 {
  73. // app.TelegramProtocolMaker = obfuscated2.MakeTelegramProtocol
  74. // }
  75. // if config.C.SecretMode != config.SecretModeTLS {
  76. // app.ClientProtocolMaker = obfuscated2.MakeClientProtocol
  77. // }
  78. app.Serve(proxyListener)
  79. return nil
  80. }