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 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. package main
  2. //go:generate scripts/generate_version.sh
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "math/rand"
  8. "os"
  9. "syscall"
  10. "time"
  11. "github.com/juju/errors"
  12. "go.uber.org/zap"
  13. "go.uber.org/zap/zapcore"
  14. kingpin "gopkg.in/alecthomas/kingpin.v2"
  15. "github.com/9seconds/mtg/config"
  16. "github.com/9seconds/mtg/ntp"
  17. "github.com/9seconds/mtg/proxy"
  18. "github.com/9seconds/mtg/stats"
  19. )
  20. var (
  21. app = kingpin.New("mtg", "Simple MTPROTO proxy.")
  22. debug = app.Flag("debug",
  23. "Run in debug mode.").
  24. Short('d').
  25. Envar("MTG_DEBUG").
  26. Bool()
  27. verbose = app.Flag("verbose",
  28. "Run in verbose mode.").
  29. Short('v').
  30. Envar("MTG_VERBOSE").
  31. Bool()
  32. bindIP = app.Flag("bind-ip",
  33. "Which IP to bind to.").
  34. Short('b').
  35. Envar("MTG_IP").
  36. Default("127.0.0.1").
  37. IP()
  38. bindPort = app.Flag("bind-port",
  39. "Which port to bind to.").
  40. Short('p').
  41. Envar("MTG_PORT").
  42. Default("3128").
  43. Uint16()
  44. publicIPv4 = app.Flag("public-ipv4",
  45. "Which IPv4 address is public.").
  46. Short('4').
  47. Envar("MTG_IPV4").
  48. IP()
  49. publicIPv4Port = app.Flag("public-ipv4-port",
  50. "Which IPv4 port is public. Default is 'bind-port' value.").
  51. Envar("MTG_IPV4_PORT").
  52. Uint16()
  53. publicIPv6 = app.Flag("public-ipv6",
  54. "Which IPv6 address is public.").
  55. Short('6').
  56. Envar("MTG_IPV6").
  57. IP()
  58. publicIPv6Port = app.Flag("public-ipv6-port",
  59. "Which IPv6 port is public. Default is 'bind-port' value.").
  60. Envar("MTG_IPV6_PORT").
  61. Uint16()
  62. statsIP = app.Flag("stats-ip",
  63. "Which IP bind stats server to.").
  64. Short('t').
  65. Envar("MTG_STATS_IP").
  66. Default("127.0.0.1").
  67. IP()
  68. statsPort = app.Flag("stats-port",
  69. "Which port bind stats to.").
  70. Short('q').
  71. Envar("MTG_STATS_PORT").
  72. Default("3129").
  73. Uint16()
  74. statsdIP = app.Flag("statsd-ip",
  75. "Which IP should we use for working with statsd.").
  76. Envar("MTG_STATSD_IP").
  77. String()
  78. statsdPort = app.Flag("statsd-port",
  79. "Which port should we use for working with statsd.").
  80. Envar("MTG_STATSD_PORT").
  81. Default("8125").
  82. Uint16()
  83. statsdNetwork = app.Flag("statsd-network",
  84. "Which network is used to work with statsd. Only 'tcp' and 'udp' are supported.").
  85. Envar("MTG_STATSD_NETWORK").
  86. Default("udp").
  87. String()
  88. statsdPrefix = app.Flag("statsd-prefix",
  89. "Which bucket prefix should we use for sending stats to statsd.").
  90. Envar("MTG_STATSD_PREFIX").
  91. Default("mtg").
  92. String()
  93. statsdTagsFormat = app.Flag("statsd-tags-format",
  94. "Which tag format should we use to send stats metrics. Valid options are 'datadog' and 'influxdb'.").
  95. Envar("MTG_STATSD_TAGS_FORMAT").
  96. String()
  97. statsdTags = app.Flag("statsd-tags",
  98. "Tags to use for working with statsd (specified as 'key=value').").
  99. Envar("MTG_STATSD_TAGS").
  100. StringMap()
  101. secret = app.Arg("secret", "Secret of this proxy.").Required().String()
  102. adtag = app.Arg("adtag", "ADTag of the proxy.").String()
  103. )
  104. func init() {
  105. rand.Seed(time.Now().UTC().UnixNano())
  106. app.Version(version)
  107. }
  108. func main() {
  109. kingpin.MustParse(app.Parse(os.Args[1:]))
  110. err := setRLimit()
  111. if err != nil {
  112. usage(err.Error())
  113. }
  114. conf, err := config.NewConfig(*debug, *verbose,
  115. *bindIP, *bindPort,
  116. *publicIPv4, *publicIPv4Port,
  117. *publicIPv6, *publicIPv6Port,
  118. *statsIP, *statsPort,
  119. *secret, *adtag,
  120. *statsdIP, *statsdPort, *statsdNetwork, *statsdPrefix,
  121. *statsdTagsFormat, *statsdTags,
  122. )
  123. if err != nil {
  124. usage(err.Error())
  125. }
  126. atom := zap.NewAtomicLevel()
  127. if conf.Debug {
  128. atom.SetLevel(zapcore.DebugLevel)
  129. } else if conf.Verbose {
  130. atom.SetLevel(zapcore.InfoLevel)
  131. } else {
  132. atom.SetLevel(zapcore.ErrorLevel)
  133. }
  134. encoderCfg := zap.NewProductionEncoderConfig()
  135. logger := zap.New(zapcore.NewCore(
  136. zapcore.NewJSONEncoder(encoderCfg),
  137. zapcore.Lock(os.Stderr),
  138. atom,
  139. ))
  140. zap.ReplaceGlobals(logger)
  141. defer logger.Sync() // nolint: errcheck
  142. printURLs(conf.GetURLs())
  143. if conf.UseMiddleProxy() {
  144. zap.S().Infow("Use middle proxy connection to Telegram")
  145. if diff, err := ntp.Fetch(); err != nil {
  146. zap.S().Warnw("Could not fetch time data from NTP")
  147. } else {
  148. if diff >= time.Second {
  149. usage(fmt.Sprintf("You choose to use middle proxy but your clock drift (%s) "+
  150. "is bigger than 1 second. Please, sync your time", diff))
  151. }
  152. go ntp.AutoUpdate()
  153. }
  154. } else {
  155. zap.S().Infow("Use direct connection to Telegram")
  156. }
  157. if err := stats.Start(conf); err != nil {
  158. panic(err)
  159. }
  160. server := proxy.NewProxy(conf)
  161. if err := server.Serve(); err != nil {
  162. zap.S().Fatalw("Server stopped", "error", err)
  163. }
  164. }
  165. func setRLimit() (err error) {
  166. rLimit := syscall.Rlimit{}
  167. err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
  168. if err != nil {
  169. err = errors.Annotate(err, "Cannot get rlimit")
  170. return
  171. }
  172. rLimit.Cur = rLimit.Max
  173. err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
  174. if err != nil {
  175. err = errors.Annotate(err, "Cannot set rlimit")
  176. }
  177. return
  178. }
  179. func printURLs(data interface{}) {
  180. encoder := json.NewEncoder(os.Stdout)
  181. encoder.SetEscapeHTML(false)
  182. encoder.SetIndent("", " ")
  183. err := encoder.Encode(data)
  184. if err != nil {
  185. panic(err)
  186. }
  187. }
  188. func usage(msg string) {
  189. io.WriteString(os.Stderr, msg+"\n") // nolint: errcheck
  190. os.Exit(1)
  191. }