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.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. // HandshakeTimeout is a timeout during which all handshake ceremonies must
  70. // be completed, otherwise this process will be aborted
  71. //
  72. // This is an optional setting.
  73. HandshakeTimeout time.Duration
  74. // TolerateTimeSkewness is a time boundary that defines a time range where
  75. // faketls timestamp is acceptable.
  76. //
  77. // This means that if if you got a timestamp X, now is Y, then if |X-Y| <
  78. // TolerateTimeSkewness, then you accept a packet.
  79. //
  80. // This is an optional setting.
  81. TolerateTimeSkewness time.Duration
  82. // PreferIP defines an IP connectivity preference. Valid values are:
  83. // 'prefer-ipv4', 'prefer-ipv6', 'only-ipv4', 'only-ipv6'.
  84. //
  85. // This is an optional setting.
  86. PreferIP string
  87. // AutoUpdate defines if it is required to auto update proxy list from
  88. // Telegram instead of relying on a hardcoded list.
  89. //
  90. // This is an optional setting.
  91. AutoUpdate bool
  92. // DomainFrontingPort is a port we use to connect to a fronting domain.
  93. //
  94. // This is required because secret does not specify a port. It specifies a
  95. // hostname only.
  96. //
  97. // This is an optional setting.
  98. DomainFrontingPort uint
  99. // DomainFrontingIP is an IP address to use when connecting to the fronting
  100. // domain instead of resolving the hostname from the secret via DNS.
  101. //
  102. // This is useful when DNS resolution of the fronting host is blocked.
  103. // The hostname from the secret is still used for SNI in the TLS handshake.
  104. //
  105. // This is an optional setting.
  106. DomainFrontingIP string
  107. // DomainFrontingProxyProtocol is used if communication between upstream
  108. // endpoint and mtg supports proxy protocol. This is useful in case
  109. // if mtg is also placed behind load balancer, and this will make
  110. // fronting webserver to know about real IP addresses
  111. //
  112. // This is an optional setting.
  113. DomainFrontingProxyProtocol bool
  114. // AllowFallbackOnUnknownDC defines how proxy behaves if unknown DC was
  115. // requested. If this setting is set to false, then such connection will be
  116. // rejected. Otherwise, proxy will chose any DC.
  117. //
  118. // Telegram is designed in a way that any DC can serve any request, the
  119. // problem is a latency.
  120. //
  121. // This is an optional setting.
  122. AllowFallbackOnUnknownDC bool
  123. // UseTestDCs defines if we have to connect to production or to staging DCs of
  124. // Telegram.
  125. //
  126. // This is required if you use mtglib as an integration library for your
  127. // Telegram-related projects.
  128. //
  129. // This is an optional setting.
  130. //
  131. // OBSOLETE and DEPRECATED. Ignored.
  132. UseTestDCs bool
  133. // DCOverrides defines a set of IP addresses that should be used
  134. // with a higher priority to those that are calculated somehow by mtg.
  135. //
  136. // OBSOLETE and DEPRECATED. Ignored.
  137. DCOverrides map[int][]string
  138. // DoppelGangerURLs is a list of URLs that should be crawled by
  139. // mtg to calculate parameters for statistical distribution of a
  140. // traffic for fronting domains. If nothing is given, then predefined
  141. // statistics is going to be used.
  142. DoppelGangerURLs []string
  143. // DoppelGangerPerRaid defines how many time each URL from
  144. // DoppelGangerURLs list should be crawled per raid. We recommend to
  145. // have this number ~10.
  146. DoppelGangerPerRaid uint
  147. // DoppelGangerEach defines a time period between each raid. We recommend
  148. // to use hours here.
  149. DoppelGangerEach time.Duration
  150. // DoppelGangerDRS defines if TLS Dynamic Record Sizing is active.
  151. DoppelGangerDRS bool
  152. // APIBindTo is the address to bind the stats HTTP API server to.
  153. // If empty, the stats API server is not started.
  154. //
  155. // This is an optional setting.
  156. APIBindTo string
  157. // ThrottleMaxConnections is the total connection limit. When total
  158. // connections exceed this value, per-user caps are computed using
  159. // a fair-share algorithm and new connections from over-cap users
  160. // are rejected. 0 disables throttling.
  161. //
  162. // This is an optional setting.
  163. ThrottleMaxConnections uint
  164. // ThrottleCheckInterval is how often the throttle recomputes per-user
  165. // caps. Defaults to 5 seconds.
  166. //
  167. // This is an optional setting.
  168. ThrottleCheckInterval time.Duration
  169. }
  170. func (p ProxyOpts) valid() error {
  171. switch {
  172. case p.Network == nil:
  173. return ErrNetworkIsNotDefined
  174. case p.AntiReplayCache == nil:
  175. return ErrAntiReplayCacheIsNotDefined
  176. case p.IPBlocklist == nil:
  177. return ErrIPBlocklistIsNotDefined
  178. case p.IPAllowlist == nil:
  179. return ErrIPAllowlistIsNotDefined
  180. case p.EventStream == nil:
  181. return ErrEventStreamIsNotDefined
  182. case p.Logger == nil:
  183. return ErrLoggerIsNotDefined
  184. }
  185. secrets := p.getSecrets()
  186. if len(secrets) == 0 {
  187. return ErrSecretInvalid
  188. }
  189. var host string
  190. for _, s := range secrets {
  191. if !s.Valid() {
  192. return ErrSecretInvalid
  193. }
  194. if host == "" {
  195. host = s.Host
  196. } else if s.Host != host {
  197. return fmt.Errorf("all secrets must use the same hostname, got %q and %q", host, s.Host)
  198. }
  199. }
  200. return nil
  201. }
  202. // getSecrets returns the effective secrets map. If Secrets is populated, it is
  203. // returned directly. Otherwise the single Secret is wrapped in a map.
  204. func (p ProxyOpts) getSecrets() map[string]Secret {
  205. if len(p.Secrets) > 0 {
  206. return p.Secrets
  207. }
  208. if p.Secret.Valid() {
  209. return map[string]Secret{"default": p.Secret}
  210. }
  211. return nil
  212. }
  213. func (p ProxyOpts) getConcurrency() int {
  214. if p.Concurrency == 0 {
  215. return DefaultConcurrency
  216. }
  217. return int(p.Concurrency)
  218. }
  219. func (p ProxyOpts) getDomainFrontingPort() int {
  220. if p.DomainFrontingPort == 0 {
  221. return DefaultDomainFrontingPort
  222. }
  223. return int(p.DomainFrontingPort)
  224. }
  225. func (p ProxyOpts) getTolerateTimeSkewness() time.Duration {
  226. if p.TolerateTimeSkewness == 0 {
  227. return DefaultTolerateTimeSkewness
  228. }
  229. return p.TolerateTimeSkewness
  230. }
  231. func (p ProxyOpts) getPreferIP() string {
  232. if p.PreferIP == "" {
  233. return DefaultPreferIP
  234. }
  235. return p.PreferIP
  236. }
  237. func (p ProxyOpts) getHandshakeTimeout() time.Duration {
  238. if p.HandshakeTimeout == 0 {
  239. return DefaultHandshakeTimeout
  240. }
  241. return p.HandshakeTimeout
  242. }
  243. func (p ProxyOpts) getIdleTimeout() time.Duration {
  244. if p.IdleTimeout == 0 {
  245. return DefaultIdleTimeout
  246. }
  247. return p.IdleTimeout
  248. }
  249. func (p ProxyOpts) getThrottleCheckInterval() time.Duration {
  250. if p.ThrottleCheckInterval == 0 {
  251. return 5 * time.Second //nolint: mnd
  252. }
  253. return p.ThrottleCheckInterval
  254. }
  255. func (p ProxyOpts) getLogger(name string) Logger {
  256. return p.Logger.Named(name)
  257. }