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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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, *publicIPv4, *publicIPv6, *statsIP,
  116. *bindPort, *publicIPv4Port, *publicIPv6Port, *statsPort, *statsdPort,
  117. *secret, *adtag, *statsdIP, *statsdNetwork, *statsdPrefix, *statsdTagsFormat,
  118. *statsdTags,
  119. )
  120. if err != nil {
  121. usage(err.Error())
  122. }
  123. atom := zap.NewAtomicLevel()
  124. switch {
  125. case conf.Debug:
  126. atom.SetLevel(zapcore.DebugLevel)
  127. case conf.Verbose:
  128. atom.SetLevel(zapcore.InfoLevel)
  129. default:
  130. atom.SetLevel(zapcore.ErrorLevel)
  131. }
  132. encoderCfg := zap.NewProductionEncoderConfig()
  133. logger := zap.New(zapcore.NewCore(
  134. zapcore.NewJSONEncoder(encoderCfg),
  135. zapcore.Lock(os.Stderr),
  136. atom,
  137. ))
  138. zap.ReplaceGlobals(logger)
  139. defer logger.Sync() // nolint: errcheck
  140. printURLs(conf.GetURLs())
  141. if conf.UseMiddleProxy() {
  142. zap.S().Infow("Use middle proxy connection to Telegram")
  143. if diff, err := ntp.Fetch(); err != nil {
  144. zap.S().Warnw("Could not fetch time data from NTP")
  145. } else {
  146. if diff >= time.Second {
  147. usage(fmt.Sprintf("You choose to use middle proxy but your clock drift (%s) "+
  148. "is bigger than 1 second. Please, sync your time", diff))
  149. }
  150. go ntp.AutoUpdate()
  151. }
  152. } else {
  153. zap.S().Infow("Use direct connection to Telegram")
  154. }
  155. if err := stats.Start(conf); err != nil {
  156. panic(err)
  157. }
  158. server := proxy.NewProxy(conf)
  159. if err := server.Serve(); err != nil {
  160. zap.S().Fatalw("Server stopped", "error", err)
  161. }
  162. }
  163. func setRLimit() (err error) {
  164. rLimit := syscall.Rlimit{}
  165. err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
  166. if err != nil {
  167. err = errors.Annotate(err, "Cannot get rlimit")
  168. return
  169. }
  170. rLimit.Cur = rLimit.Max
  171. err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
  172. if err != nil {
  173. err = errors.Annotate(err, "Cannot set rlimit")
  174. }
  175. return
  176. }
  177. func printURLs(data interface{}) {
  178. encoder := json.NewEncoder(os.Stdout)
  179. encoder.SetEscapeHTML(false)
  180. encoder.SetIndent("", " ")
  181. err := encoder.Encode(data)
  182. if err != nil {
  183. panic(err)
  184. }
  185. }
  186. func usage(msg string) {
  187. io.WriteString(os.Stderr, msg+"\n") // nolint: errcheck
  188. os.Exit(1)
  189. }