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.

main.go 5.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. writeBufferSize = app.Flag("write-buffer",
  45. "Write buffer size in bytes. You can think about it as a buffer from client to Telegram.").
  46. Short('w').
  47. Envar("MTG_BUFFER_WRITE").
  48. Default("65536").
  49. Uint32()
  50. readBufferSize = app.Flag("read-buffer",
  51. "Read buffer size in bytes. You can think about it as a buffer from Telegram to client.").
  52. Short('r').
  53. Envar("MTG_BUFFER_READ").
  54. Default("131072").
  55. Uint32()
  56. publicIPv4 = app.Flag("public-ipv4",
  57. "Which IPv4 address is public.").
  58. Short('4').
  59. Envar("MTG_IPV4").
  60. IP()
  61. publicIPv4Port = app.Flag("public-ipv4-port",
  62. "Which IPv4 port is public. Default is 'bind-port' value.").
  63. Envar("MTG_IPV4_PORT").
  64. Uint16()
  65. publicIPv6 = app.Flag("public-ipv6",
  66. "Which IPv6 address is public.").
  67. Short('6').
  68. Envar("MTG_IPV6").
  69. IP()
  70. publicIPv6Port = app.Flag("public-ipv6-port",
  71. "Which IPv6 port is public. Default is 'bind-port' value.").
  72. Envar("MTG_IPV6_PORT").
  73. Uint16()
  74. statsIP = app.Flag("stats-ip",
  75. "Which IP bind stats server to.").
  76. Short('t').
  77. Envar("MTG_STATS_IP").
  78. Default("127.0.0.1").
  79. IP()
  80. statsPort = app.Flag("stats-port",
  81. "Which port bind stats to.").
  82. Short('q').
  83. Envar("MTG_STATS_PORT").
  84. Default("3129").
  85. Uint16()
  86. statsdIP = app.Flag("statsd-ip",
  87. "Which IP should we use for working with statsd.").
  88. Envar("MTG_STATSD_IP").
  89. String()
  90. statsdPort = app.Flag("statsd-port",
  91. "Which port should we use for working with statsd.").
  92. Envar("MTG_STATSD_PORT").
  93. Default("8125").
  94. Uint16()
  95. statsdNetwork = app.Flag("statsd-network",
  96. "Which network is used to work with statsd. Only 'tcp' and 'udp' are supported.").
  97. Envar("MTG_STATSD_NETWORK").
  98. Default("udp").
  99. String()
  100. statsdPrefix = app.Flag("statsd-prefix",
  101. "Which bucket prefix should we use for sending stats to statsd.").
  102. Envar("MTG_STATSD_PREFIX").
  103. Default("mtg").
  104. String()
  105. statsdTagsFormat = app.Flag("statsd-tags-format",
  106. "Which tag format should we use to send stats metrics. Valid options are 'datadog' and 'influxdb'.").
  107. Envar("MTG_STATSD_TAGS_FORMAT").
  108. String()
  109. statsdTags = app.Flag("statsd-tags",
  110. "Tags to use for working with statsd (specified as 'key=value').").
  111. Envar("MTG_STATSD_TAGS").
  112. StringMap()
  113. secret = app.Arg("secret", "Secret of this proxy.").Required().HexBytes()
  114. adtag = app.Arg("adtag", "ADTag of the proxy.").HexBytes()
  115. )
  116. func init() {
  117. rand.Seed(time.Now().UTC().UnixNano())
  118. app.Version(version)
  119. app.HelpFlag.Short('h')
  120. }
  121. func main() { // nolint: gocyclo
  122. kingpin.MustParse(app.Parse(os.Args[1:]))
  123. err := setRLimit()
  124. if err != nil {
  125. usage(err.Error())
  126. }
  127. conf, err := config.NewConfig(*debug, *verbose,
  128. *writeBufferSize, *readBufferSize,
  129. *bindIP, *publicIPv4, *publicIPv6, *statsIP,
  130. *bindPort, *publicIPv4Port, *publicIPv6Port, *statsPort, *statsdPort,
  131. *statsdIP, *statsdNetwork, *statsdPrefix, *statsdTagsFormat,
  132. *statsdTags,
  133. *secret, *adtag,
  134. )
  135. if err != nil {
  136. usage(err.Error())
  137. }
  138. atom := zap.NewAtomicLevel()
  139. switch {
  140. case conf.Debug:
  141. atom.SetLevel(zapcore.DebugLevel)
  142. case conf.Verbose:
  143. atom.SetLevel(zapcore.InfoLevel)
  144. default:
  145. atom.SetLevel(zapcore.ErrorLevel)
  146. }
  147. encoderCfg := zap.NewProductionEncoderConfig()
  148. logger := zap.New(zapcore.NewCore(
  149. zapcore.NewJSONEncoder(encoderCfg),
  150. zapcore.Lock(os.Stderr),
  151. atom,
  152. ))
  153. zap.ReplaceGlobals(logger)
  154. defer logger.Sync() // nolint: errcheck
  155. printURLs(conf.GetURLs())
  156. if conf.UseMiddleProxy() {
  157. zap.S().Infow("Use middle proxy connection to Telegram")
  158. if diff, err := ntp.Fetch(); err != nil {
  159. zap.S().Warnw("Could not fetch time data from NTP")
  160. } else {
  161. if diff >= time.Second {
  162. usage(fmt.Sprintf("You choose to use middle proxy but your clock drift (%s) "+
  163. "is bigger than 1 second. Please, sync your time", diff))
  164. }
  165. go ntp.AutoUpdate()
  166. }
  167. } else {
  168. zap.S().Infow("Use direct connection to Telegram")
  169. }
  170. if err := stats.Start(conf); err != nil {
  171. panic(err)
  172. }
  173. server := proxy.NewProxy(conf)
  174. if err := server.Serve(); err != nil {
  175. zap.S().Fatalw("Server stopped", "error", err)
  176. }
  177. }
  178. func setRLimit() (err error) {
  179. rLimit := syscall.Rlimit{}
  180. err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
  181. if err != nil {
  182. err = errors.Annotate(err, "Cannot get rlimit")
  183. return
  184. }
  185. rLimit.Cur = rLimit.Max
  186. err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
  187. if err != nil {
  188. err = errors.Annotate(err, "Cannot set rlimit")
  189. }
  190. return
  191. }
  192. func printURLs(data interface{}) {
  193. encoder := json.NewEncoder(os.Stdout)
  194. encoder.SetEscapeHTML(false)
  195. encoder.SetIndent("", " ")
  196. err := encoder.Encode(data)
  197. if err != nil {
  198. panic(err)
  199. }
  200. }
  201. func usage(msg string) {
  202. io.WriteString(os.Stderr, msg+"\n") // nolint: errcheck
  203. os.Exit(1)
  204. }