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文字以内のものにしてください。

doctor.go 11KB

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