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.

doctor.go 11KB

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