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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. package cli
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "maps"
  7. "net"
  8. "os"
  9. "slices"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "text/template"
  14. "time"
  15. "github.com/9seconds/mtg/v2/essentials"
  16. "github.com/9seconds/mtg/v2/internal/config"
  17. "github.com/9seconds/mtg/v2/internal/utils"
  18. "github.com/9seconds/mtg/v2/mtglib"
  19. "github.com/9seconds/mtg/v2/network/v2"
  20. "github.com/beevik/ntp"
  21. )
  22. var (
  23. tplError = template.Must(
  24. template.New("").Parse(" ‼️ {{ .description }}: {{ .error }}\n"),
  25. )
  26. tplWDeprecatedConfig = template.Must(
  27. template.New("").
  28. Parse(` ⚠️ Option {{ .old | printf "%q" }}{{ if .old_section }} from section [{{ .old_section }}]{{ end }} is deprecated and will be removed in v{{ .when }}. Please use {{ .new | printf "%q" }}{{ if .new_section }} in [{{ .new_section }}] section{{ end }} instead.` + "\n"),
  29. )
  30. tplOTimeSkewness = template.Must(
  31. template.New("").
  32. Parse(" ✅ Time drift is {{ .drift }}, but tolerate-time-skewness is {{ .value }}\n"),
  33. )
  34. tplWTimeSkewness = template.Must(
  35. template.New("").
  36. Parse(" ⚠️ Time drift is {{ .drift }}, but tolerate-time-skewness is {{ .value }}. Please check ntp.\n"),
  37. )
  38. tplETimeSkewness = template.Must(
  39. template.New("").
  40. Parse(" ❌ Time drift is {{ .drift }}, but tolerate-time-skewness is {{ .value }}. You will get many rejected connections!\n"),
  41. )
  42. tplODCConnect = template.Must(
  43. template.New("").Parse(" ✅ DC {{ .dc }}\n"),
  44. )
  45. tplEDCConnect = template.Must(
  46. template.New("").Parse(" ❌ DC {{ .dc }}: {{ .error }}\n"),
  47. )
  48. tplODNSSNIMatch = template.Must(
  49. template.New("").Parse(" ✅ IP address {{ .ip }} matches secret hostname {{ .hostname }}\n"),
  50. )
  51. tplEDNSSNIMatch = template.Must(
  52. template.New("").Parse(" ❌ Hostname {{ .hostname }} {{ if .resolved }}is resolved to {{ .resolved }} addresses, not {{ if .ip4 }}{{ .ip4 }}{{ else }}{{ .ip6 }}{{ end }}{{ else }}cannot be resolved to any host{{ end }}\n"),
  53. )
  54. tplOFrontingDomain = template.Must(
  55. template.New("").Parse(" ✅ {{ .address }} is reachable\n"),
  56. )
  57. tplEFrontingDomain = template.Must(
  58. template.New("").Parse(" ❌ {{ .address }}: {{ .error }}\n"),
  59. )
  60. )
  61. type Doctor struct {
  62. conf *config.Config
  63. ConfigPath string `kong:"arg,required,type='existingfile',help='Path to the configuration file.',name='config-path'"` //nolint: lll
  64. }
  65. func (d *Doctor) Run(cli *CLI, version string) error {
  66. conf, err := utils.ReadConfig(d.ConfigPath)
  67. if err != nil {
  68. return fmt.Errorf("cannot init config: %w", err)
  69. }
  70. d.conf = conf
  71. fmt.Println("Deprecated options")
  72. everythingOK := d.checkDeprecatedConfig()
  73. fmt.Println("Time skewness")
  74. everythingOK = d.checkTimeSkewness() && everythingOK
  75. resolver, err := network.GetDNS(conf.GetDNS())
  76. if err != nil {
  77. return fmt.Errorf("cannot create DNS resolver: %w", err)
  78. }
  79. base := network.New(
  80. resolver,
  81. "",
  82. conf.Network.Timeout.TCP.Get(10*time.Second),
  83. conf.Network.Timeout.HTTP.Get(0),
  84. conf.Network.Timeout.Idle.Get(0),
  85. net.KeepAliveConfig{
  86. Enable: !conf.Network.KeepAlive.Disabled.Get(false),
  87. Idle: conf.Network.KeepAlive.Idle.Get(0),
  88. Interval: conf.Network.KeepAlive.Interval.Get(0),
  89. Count: int(conf.Network.KeepAlive.Count.Get(0)),
  90. },
  91. )
  92. fmt.Println("Validate native network connectivity")
  93. everythingOK = d.checkNetwork(base) && everythingOK
  94. for _, url := range conf.Network.Proxies {
  95. value, err := network.NewProxyNetwork(base, url.Get(nil))
  96. if err != nil {
  97. return err
  98. }
  99. fmt.Printf("Validate network connectivity with proxy %s\n", url.Get(nil))
  100. everythingOK = d.checkNetwork(value) && everythingOK
  101. }
  102. fmt.Println("Validate fronting domain connectivity")
  103. everythingOK = d.checkFrontingDomain(base) && everythingOK
  104. fmt.Println("Validate SNI-DNS match")
  105. everythingOK = d.checkSecretHost(resolver, base) && everythingOK
  106. if !everythingOK {
  107. os.Exit(1)
  108. }
  109. return nil
  110. }
  111. func (d *Doctor) checkDeprecatedConfig() bool {
  112. ok := true
  113. if d.conf.DomainFrontingIP.Value != nil {
  114. ok = false
  115. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  116. "when": "2.3.0",
  117. "old": "domain-fronting-ip",
  118. "old_section": "",
  119. "new": "ip",
  120. "new_section": "domain-fronting",
  121. })
  122. }
  123. if d.conf.DomainFrontingPort.Value != 0 {
  124. ok = false
  125. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  126. "when": "2.3.0",
  127. "old": "domain-fronting-port",
  128. "old_section": "",
  129. "new": "port",
  130. "new_section": "domain-fronting",
  131. })
  132. }
  133. if d.conf.DomainFrontingProxyProtocol.Value {
  134. ok = false
  135. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  136. "when": "2.3.0",
  137. "old": "domain-fronting-proxy-protocol",
  138. "old_section": "",
  139. "new": "proxy-protocol",
  140. "new_section": "domain-fronting",
  141. })
  142. }
  143. if d.conf.Network.DOHIP.Value != nil {
  144. ok = false
  145. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  146. "when": "2.3.0",
  147. "old": "doh-ip",
  148. "old_section": "network",
  149. "new": "dns",
  150. "new_section": "network",
  151. })
  152. }
  153. if ok {
  154. fmt.Println(" ✅ All good")
  155. }
  156. return ok
  157. }
  158. func (d *Doctor) checkTimeSkewness() bool {
  159. response, err := ntp.Query("0.pool.ntp.org")
  160. if err != nil {
  161. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  162. "description": "cannot access ntp pool",
  163. "error": err,
  164. })
  165. return false
  166. }
  167. skewness := response.ClockOffset.Abs()
  168. confValue := d.conf.TolerateTimeSkewness.Get(mtglib.DefaultTolerateTimeSkewness)
  169. diff := float64(skewness) / float64(confValue)
  170. tplData := map[string]any{
  171. "drift": response.ClockOffset,
  172. "value": confValue,
  173. }
  174. switch {
  175. case diff < 0.3:
  176. tplOTimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  177. return true
  178. case diff < 0.7:
  179. tplWTimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  180. default:
  181. tplETimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  182. }
  183. return false
  184. }
  185. func (d *Doctor) checkNetwork(ntw mtglib.Network) bool {
  186. dcs := slices.Collect(maps.Keys(essentials.TelegramCoreAddresses))
  187. slices.Sort(dcs)
  188. errs := make([]error, len(dcs))
  189. var wg sync.WaitGroup
  190. for i, dc := range dcs {
  191. wg.Go(func() {
  192. defer func() {
  193. if r := recover(); r != nil {
  194. errs[i] = fmt.Errorf("panic: %v", r)
  195. }
  196. }()
  197. errs[i] = d.checkNetworkAddresses(ntw, essentials.TelegramCoreAddresses[dc])
  198. })
  199. }
  200. wg.Wait()
  201. ok := true
  202. for i, dc := range dcs {
  203. if errs[i] == nil {
  204. tplODCConnect.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  205. "dc": dc,
  206. })
  207. } else {
  208. tplEDCConnect.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  209. "dc": dc,
  210. "error": errs[i],
  211. })
  212. ok = false
  213. }
  214. }
  215. return ok
  216. }
  217. func (d *Doctor) checkNetworkAddresses(ntw mtglib.Network, addresses []string) error {
  218. checkAddresses := []string{}
  219. switch d.conf.PreferIP.Get("prefer-ip4") {
  220. case "only-ipv4":
  221. for _, addr := range addresses {
  222. host, _, err := net.SplitHostPort(addr)
  223. if err != nil {
  224. panic(err)
  225. }
  226. if ip := net.ParseIP(host); ip != nil && ip.To4() != nil {
  227. checkAddresses = append(checkAddresses, addr)
  228. }
  229. }
  230. case "only-ipv6":
  231. for _, addr := range addresses {
  232. host, _, err := net.SplitHostPort(addr)
  233. if err != nil {
  234. panic(err)
  235. }
  236. if ip := net.ParseIP(host); ip != nil && ip.To4() == nil {
  237. checkAddresses = append(checkAddresses, addr)
  238. }
  239. }
  240. default:
  241. checkAddresses = addresses
  242. }
  243. if len(checkAddresses) == 0 {
  244. return fmt.Errorf("no suitable addresses after IP version filtering")
  245. }
  246. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  247. defer cancel()
  248. var (
  249. conn net.Conn
  250. err error
  251. )
  252. for _, addr := range checkAddresses {
  253. conn, err = ntw.DialContext(ctx, "tcp", addr)
  254. if err != nil {
  255. continue
  256. }
  257. conn.Close() //nolint: errcheck
  258. return nil
  259. }
  260. return err
  261. }
  262. func (d *Doctor) checkFrontingDomain(ntw mtglib.Network) bool {
  263. host := d.conf.Secret.Host
  264. if ip := d.conf.GetDomainFrontingIP(nil); ip != "" {
  265. host = ip
  266. }
  267. port := d.conf.GetDomainFrontingPort(mtglib.DefaultDomainFrontingPort)
  268. address := net.JoinHostPort(host, strconv.Itoa(int(port)))
  269. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  270. defer cancel()
  271. dialer := ntw.NativeDialer()
  272. conn, err := dialer.DialContext(ctx, "tcp", address)
  273. if err != nil {
  274. tplEFrontingDomain.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  275. "address": address,
  276. "error": err,
  277. })
  278. return false
  279. }
  280. conn.Close() //nolint: errcheck
  281. tplOFrontingDomain.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  282. "address": address,
  283. })
  284. return true
  285. }
  286. func (d *Doctor) checkSecretHost(resolver *net.Resolver, ntw mtglib.Network) bool {
  287. addresses, err := resolver.LookupIPAddr(context.Background(), d.conf.Secret.Host)
  288. if err != nil {
  289. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  290. "description": fmt.Sprintf("cannot resolve DNS name of %s", d.conf.Secret.Host),
  291. "error": err,
  292. })
  293. return false
  294. }
  295. ourIP4 := d.conf.PublicIPv4.Get(nil)
  296. if ourIP4 == nil {
  297. ourIP4 = getIP(ntw, "tcp4")
  298. }
  299. ourIP6 := d.conf.PublicIPv6.Get(nil)
  300. if ourIP6 == nil {
  301. ourIP6 = getIP(ntw, "tcp6")
  302. }
  303. if ourIP4 == nil && ourIP6 == nil {
  304. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  305. "description": "cannot detect public IP address",
  306. "error": errors.New("cannot detect automatically and public-ipv4/public-ipv6 are not set in config"),
  307. })
  308. return false
  309. }
  310. strAddresses := []string{}
  311. for _, value := range addresses {
  312. if (ourIP4 != nil && value.IP.String() == ourIP4.String()) ||
  313. (ourIP6 != nil && value.IP.String() == ourIP6.String()) {
  314. tplODNSSNIMatch.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  315. "ip": value.IP,
  316. "hostname": d.conf.Secret.Host,
  317. })
  318. return true
  319. }
  320. strAddresses = append(strAddresses, `"`+value.IP.String()+`"`)
  321. }
  322. tplEDNSSNIMatch.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  323. "hostname": d.conf.Secret.Host,
  324. "resolved": strings.Join(strAddresses, ", "),
  325. "ip4": ourIP4,
  326. "ip6": ourIP6,
  327. })
  328. return false
  329. }