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_opts.go 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package mtglib
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. // ProxyOpts is a structure with settings to mtg proxy.
  7. //
  8. // This is not required per se, but this is to shorten function signature and
  9. // give an ability to conveniently provide default values.
  10. type ProxyOpts struct {
  11. // Secret defines a secret which should be used by a proxy.
  12. //
  13. // Deprecated: Use Secrets instead for multi-secret support.
  14. // Kept for backward compatibility.
  15. Secret Secret
  16. // Secrets defines a map of named secrets which should be used by a proxy.
  17. // If set, Secret is ignored. During FakeTLS handshake, each secret is
  18. // tried until one validates.
  19. Secrets map[string]Secret
  20. // Network defines a network instance which should be used for all network
  21. // communications made by proxies.
  22. //
  23. // This is a mandatory setting.
  24. Network Network
  25. // AntiReplayCache defines an instance of antireplay cache.
  26. //
  27. // This is a mandatory setting.
  28. AntiReplayCache AntiReplayCache
  29. // IPBlocklist defines an instance of IP blocklist.
  30. //
  31. // This is a mandatory setting.
  32. IPBlocklist IPBlocklist
  33. // IPAllowlist defines a whitelist of IPs to allow to use proxy.
  34. //
  35. // This is an optional setting, ignored by default (no restrictions).
  36. IPAllowlist IPBlocklist
  37. // EventStream defines an instance of event stream.
  38. //
  39. // This ia a mandatory setting.
  40. EventStream EventStream
  41. // Logger defines an instance of the logger.
  42. //
  43. // This is a mandatory setting.
  44. Logger Logger
  45. // BufferSize is a size of the copy buffer in bytes.
  46. //
  47. // Please remember that we multiply this number in 2, because when we relay
  48. // between proxies, we have to create 2 intermediate buffers: to and from.
  49. //
  50. // This is an optional setting.
  51. //
  52. // Deprecated: this setting is no longer makes any effect.
  53. BufferSize uint
  54. // Concurrency is a size of the worker pool for connection management.
  55. //
  56. // If we have more connections than this number, they are going to be
  57. // rejected.
  58. //
  59. // This is an optional setting.
  60. Concurrency uint
  61. // IdleTimeout is a timeout for relay when we have to break a stream.
  62. //
  63. // This is a timeout for any activity. So, if we have any message which will
  64. // pass to either direction, a timer is reset. If we have no any reads or
  65. // writes for this timeout, a connection will be aborted.
  66. //
  67. // This is an optional setting.
  68. IdleTimeout time.Duration
  69. // TolerateTimeSkewness is a time boundary that defines a time range where
  70. // faketls timestamp is acceptable.
  71. //
  72. // This means that if if you got a timestamp X, now is Y, then if |X-Y| <
  73. // TolerateTimeSkewness, then you accept a packet.
  74. //
  75. // This is an optional setting.
  76. TolerateTimeSkewness time.Duration
  77. // PreferIP defines an IP connectivity preference. Valid values are:
  78. // 'prefer-ipv4', 'prefer-ipv6', 'only-ipv4', 'only-ipv6'.
  79. //
  80. // This is an optional setting.
  81. PreferIP string
  82. // AutoUpdate defines if it is required to auto update proxy list from
  83. // Telegram instead of relying on a hardcoded list.
  84. //
  85. // This is an optional setting.
  86. AutoUpdate bool
  87. // DomainFrontingPort is a port we use to connect to a fronting domain.
  88. //
  89. // This is required because secret does not specify a port. It specifies a
  90. // hostname only.
  91. //
  92. // This is an optional setting.
  93. DomainFrontingPort uint
  94. // DomainFrontingIP is an IP address to use when connecting to the fronting
  95. // domain instead of resolving the hostname from the secret via DNS.
  96. //
  97. // This is useful when DNS resolution of the fronting host is blocked.
  98. // The hostname from the secret is still used for SNI in the TLS handshake.
  99. //
  100. // This is an optional setting.
  101. DomainFrontingIP string
  102. // DomainFrontingProxyProtocol is used if communication between upstream
  103. // endpoint and mtg supports proxy protocol. This is useful in case
  104. // if mtg is also placed behind load balancer, and this will make
  105. // fronting webserver to know about real IP addresses
  106. //
  107. // This is an optional setting.
  108. DomainFrontingProxyProtocol bool
  109. // AllowFallbackOnUnknownDC defines how proxy behaves if unknown DC was
  110. // requested. If this setting is set to false, then such connection will be
  111. // rejected. Otherwise, proxy will chose any DC.
  112. //
  113. // Telegram is designed in a way that any DC can serve any request, the
  114. // problem is a latency.
  115. //
  116. // This is an optional setting.
  117. AllowFallbackOnUnknownDC bool
  118. // UseTestDCs defines if we have to connect to production or to staging DCs of
  119. // Telegram.
  120. //
  121. // This is required if you use mtglib as an integration library for your
  122. // Telegram-related projects.
  123. //
  124. // This is an optional setting.
  125. //
  126. // OBSOLETE and DEPRECATED. Ignored.
  127. UseTestDCs bool
  128. // DCOverrides defines a set of IP addresses that should be used
  129. // with a higher priority to those that are calculated somehow by mtg.
  130. //
  131. // OBSOLETE and DEPRECATED. Ignored.
  132. DCOverrides map[int][]string
  133. // DoppelGangerURLs is a list of URLs that should be crawled by
  134. // mtg to calculate parameters for statistical distribution of a
  135. // traffic for fronting domains. If nothing is given, then predefined
  136. // statistics is going to be used.
  137. DoppelGangerURLs []string
  138. // DoppelGangerPerRaid defines how many time each URL from
  139. // DoppelGangerURLs list should be crawled per raid. We recommend to
  140. // have this number ~10.
  141. DoppelGangerPerRaid uint
  142. // DoppelGangerEach defines a time period between each raid. We recommend
  143. // to use hours here.
  144. DoppelGangerEach time.Duration
  145. // DoppelGangerDRS defines if TLS Dynamic Record Sizing is active.
  146. DoppelGangerDRS bool
  147. // APIBindTo is the address to bind the stats HTTP API server to.
  148. // If empty, the stats API server is not started.
  149. //
  150. // This is an optional setting.
  151. APIBindTo string
  152. // ThrottleMaxConnections is the total connection limit. When total
  153. // connections exceed this value, per-user caps are computed using
  154. // a fair-share algorithm and new connections from over-cap users
  155. // are rejected. 0 disables throttling.
  156. //
  157. // This is an optional setting.
  158. ThrottleMaxConnections uint
  159. // ThrottleCheckInterval is how often the throttle recomputes per-user
  160. // caps. Defaults to 5 seconds.
  161. //
  162. // This is an optional setting.
  163. ThrottleCheckInterval time.Duration
  164. }
  165. func (p ProxyOpts) valid() error {
  166. switch {
  167. case p.Network == nil:
  168. return ErrNetworkIsNotDefined
  169. case p.AntiReplayCache == nil:
  170. return ErrAntiReplayCacheIsNotDefined
  171. case p.IPBlocklist == nil:
  172. return ErrIPBlocklistIsNotDefined
  173. case p.IPAllowlist == nil:
  174. return ErrIPAllowlistIsNotDefined
  175. case p.EventStream == nil:
  176. return ErrEventStreamIsNotDefined
  177. case p.Logger == nil:
  178. return ErrLoggerIsNotDefined
  179. }
  180. secrets := p.getSecrets()
  181. if len(secrets) == 0 {
  182. return ErrSecretInvalid
  183. }
  184. var host string
  185. for _, s := range secrets {
  186. if !s.Valid() {
  187. return ErrSecretInvalid
  188. }
  189. if host == "" {
  190. host = s.Host
  191. } else if s.Host != host {
  192. return fmt.Errorf("all secrets must use the same hostname, got %q and %q", host, s.Host)
  193. }
  194. }
  195. return nil
  196. }
  197. // getSecrets returns the effective secrets map. If Secrets is populated, it is
  198. // returned directly. Otherwise the single Secret is wrapped in a map.
  199. func (p ProxyOpts) getSecrets() map[string]Secret {
  200. if len(p.Secrets) > 0 {
  201. return p.Secrets
  202. }
  203. if p.Secret.Valid() {
  204. return map[string]Secret{"default": p.Secret}
  205. }
  206. return nil
  207. }
  208. func (p ProxyOpts) getConcurrency() int {
  209. if p.Concurrency == 0 {
  210. return DefaultConcurrency
  211. }
  212. return int(p.Concurrency)
  213. }
  214. func (p ProxyOpts) getDomainFrontingPort() int {
  215. if p.DomainFrontingPort == 0 {
  216. return DefaultDomainFrontingPort
  217. }
  218. return int(p.DomainFrontingPort)
  219. }
  220. func (p ProxyOpts) getTolerateTimeSkewness() time.Duration {
  221. if p.TolerateTimeSkewness == 0 {
  222. return DefaultTolerateTimeSkewness
  223. }
  224. return p.TolerateTimeSkewness
  225. }
  226. func (p ProxyOpts) getPreferIP() string {
  227. if p.PreferIP == "" {
  228. return DefaultPreferIP
  229. }
  230. return p.PreferIP
  231. }
  232. func (p ProxyOpts) getIdleTimeout() time.Duration {
  233. if p.IdleTimeout == 0 {
  234. return time.Minute
  235. }
  236. return p.IdleTimeout
  237. }
  238. func (p ProxyOpts) getThrottleCheckInterval() time.Duration {
  239. if p.ThrottleCheckInterval == 0 {
  240. return 5 * time.Second //nolint: mnd
  241. }
  242. return p.ThrottleCheckInterval
  243. }
  244. func (p ProxyOpts) getLogger(name string) Logger {
  245. return p.Logger.Named(name)
  246. }