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
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

doctor.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 }}is resolved to {{ .resolved }} addresses, not {{ if .ip4 }}{{ .ip4 }}{{ else }}{{ .ip6 }}{{ end }}{{ 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. )
  94. fmt.Println("Validate native network connectivity")
  95. if d.SkipNativeCheck {
  96. fmt.Println(" ⏭ Skipped (--skip-native-check)")
  97. } else {
  98. everythingOK = d.checkNetwork(base) && everythingOK
  99. }
  100. for _, url := range conf.Network.Proxies {
  101. value, err := network.NewProxyNetwork(base, url.Get(nil))
  102. if err != nil {
  103. return err
  104. }
  105. fmt.Printf("Validate network connectivity with proxy %s\n", url.Get(nil))
  106. everythingOK = d.checkNetwork(value) && everythingOK
  107. }
  108. fmt.Println("Validate fronting domain connectivity")
  109. everythingOK = d.checkFrontingDomain(base) && everythingOK
  110. fmt.Println("Validate SNI-DNS match")
  111. everythingOK = d.checkSecretHost(resolver, base) && everythingOK
  112. if !everythingOK {
  113. os.Exit(1)
  114. }
  115. return nil
  116. }
  117. func (d *Doctor) checkDeprecatedConfig() bool {
  118. ok := true
  119. if d.conf.DomainFrontingIP.Value != nil {
  120. ok = false
  121. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  122. "when": "2.3.0",
  123. "old": "domain-fronting-ip",
  124. "old_section": "",
  125. "new": "host",
  126. "new_section": "domain-fronting",
  127. })
  128. }
  129. if d.conf.DomainFronting.IP.Value != nil {
  130. ok = false
  131. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  132. "when": "2.4.0",
  133. "old": "ip",
  134. "old_section": "domain-fronting",
  135. "new": "host",
  136. "new_section": "domain-fronting",
  137. })
  138. }
  139. if d.conf.DomainFrontingPort.Value != 0 {
  140. ok = false
  141. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  142. "when": "2.3.0",
  143. "old": "domain-fronting-port",
  144. "old_section": "",
  145. "new": "port",
  146. "new_section": "domain-fronting",
  147. })
  148. }
  149. if d.conf.DomainFrontingProxyProtocol.Value {
  150. ok = false
  151. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  152. "when": "2.3.0",
  153. "old": "domain-fronting-proxy-protocol",
  154. "old_section": "",
  155. "new": "proxy-protocol",
  156. "new_section": "domain-fronting",
  157. })
  158. }
  159. if d.conf.Network.DOHIP.Value != nil {
  160. ok = false
  161. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  162. "when": "2.3.0",
  163. "old": "doh-ip",
  164. "old_section": "network",
  165. "new": "dns",
  166. "new_section": "network",
  167. })
  168. }
  169. if ok {
  170. fmt.Println(" ✅ All good")
  171. }
  172. return ok
  173. }
  174. func (d *Doctor) checkTimeSkewness() bool {
  175. response, err := ntp.Query("0.pool.ntp.org")
  176. if err != nil {
  177. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  178. "description": "cannot access ntp pool",
  179. "error": err,
  180. })
  181. return false
  182. }
  183. skewness := response.ClockOffset.Abs()
  184. confValue := d.conf.TolerateTimeSkewness.Get(mtglib.DefaultTolerateTimeSkewness)
  185. diff := float64(skewness) / float64(confValue)
  186. tplData := map[string]any{
  187. "drift": response.ClockOffset,
  188. "value": confValue,
  189. }
  190. switch {
  191. case diff < 0.3:
  192. tplOTimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  193. return true
  194. case diff < 0.7:
  195. tplWTimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  196. default:
  197. tplETimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  198. }
  199. return false
  200. }
  201. func (d *Doctor) checkNetwork(ntw mtglib.Network) bool {
  202. dcs := slices.Collect(maps.Keys(essentials.TelegramCoreAddresses))
  203. slices.Sort(dcs)
  204. type dcResult struct {
  205. rtt time.Duration
  206. err error
  207. }
  208. results := make([]dcResult, len(dcs))
  209. var wg sync.WaitGroup
  210. for i, dc := range dcs {
  211. wg.Go(func() {
  212. defer func() {
  213. if r := recover(); r != nil {
  214. results[i].err = fmt.Errorf("panic: %v", r)
  215. }
  216. }()
  217. results[i].rtt, results[i].err = d.checkNetworkAddresses(ntw, dc, essentials.TelegramCoreAddresses[dc])
  218. })
  219. }
  220. wg.Wait()
  221. ok := true
  222. for i, dc := range dcs {
  223. if results[i].err == nil {
  224. tplODCConnect.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  225. "dc": dc,
  226. "rtt": results[i].rtt.Round(time.Microsecond),
  227. })
  228. } else {
  229. tplEDCConnect.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  230. "dc": dc,
  231. "error": results[i].err,
  232. })
  233. ok = false
  234. }
  235. }
  236. return ok
  237. }
  238. func (d *Doctor) checkNetworkAddresses(ntw mtglib.Network, dc int, addresses []string) (time.Duration, error) {
  239. checkAddresses := []string{}
  240. switch d.conf.PreferIP.Get("prefer-ip4") {
  241. case "only-ipv4":
  242. for _, addr := range addresses {
  243. host, _, err := net.SplitHostPort(addr)
  244. if err != nil {
  245. panic(err)
  246. }
  247. if ip := net.ParseIP(host); ip != nil && ip.To4() != nil {
  248. checkAddresses = append(checkAddresses, addr)
  249. }
  250. }
  251. case "only-ipv6":
  252. for _, addr := range addresses {
  253. host, _, err := net.SplitHostPort(addr)
  254. if err != nil {
  255. panic(err)
  256. }
  257. if ip := net.ParseIP(host); ip != nil && ip.To4() == nil {
  258. checkAddresses = append(checkAddresses, addr)
  259. }
  260. }
  261. default:
  262. checkAddresses = addresses
  263. }
  264. if len(checkAddresses) == 0 {
  265. return 0, fmt.Errorf("no suitable addresses after IP version filtering")
  266. }
  267. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  268. defer cancel()
  269. var lastErr error
  270. for _, addr := range checkAddresses {
  271. conn, err := ntw.DialContext(ctx, "tcp", addr)
  272. if err != nil {
  273. lastErr = fmt.Errorf("tcp connect to %s: %w", addr, err)
  274. continue
  275. }
  276. rtt, err := dcprobe.Probe(ctx, conn, dc)
  277. conn.Close() //nolint: errcheck
  278. if err != nil {
  279. lastErr = fmt.Errorf("rpc handshake to %s: %w", addr, err)
  280. continue
  281. }
  282. return rtt, nil
  283. }
  284. return 0, lastErr
  285. }
  286. func (d *Doctor) checkFrontingDomain(ntw mtglib.Network) bool {
  287. host := d.conf.Secret.Host
  288. if override := d.conf.GetDomainFrontingHost(); override != "" {
  289. host = override
  290. }
  291. port := d.conf.GetDomainFrontingPort(mtglib.DefaultDomainFrontingPort)
  292. address := net.JoinHostPort(host, strconv.Itoa(int(port)))
  293. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  294. defer cancel()
  295. dialer := ntw.NativeDialer()
  296. conn, err := dialer.DialContext(ctx, "tcp", address)
  297. if err != nil {
  298. tplEFrontingDomain.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  299. "address": address,
  300. "error": err,
  301. })
  302. return false
  303. }
  304. conn.Close() //nolint: errcheck
  305. tplOFrontingDomain.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  306. "address": address,
  307. })
  308. return true
  309. }
  310. func (d *Doctor) checkSecretHost(resolver *net.Resolver, ntw mtglib.Network) bool {
  311. addresses, err := resolver.LookupIPAddr(context.Background(), d.conf.Secret.Host)
  312. if err != nil {
  313. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  314. "description": fmt.Sprintf("cannot resolve DNS name of %s", d.conf.Secret.Host),
  315. "error": err,
  316. })
  317. return false
  318. }
  319. ourIP4 := d.conf.PublicIPv4.Get(nil)
  320. if ourIP4 == nil {
  321. ourIP4 = getIP(ntw, "tcp4")
  322. }
  323. ourIP6 := d.conf.PublicIPv6.Get(nil)
  324. if ourIP6 == nil {
  325. ourIP6 = getIP(ntw, "tcp6")
  326. }
  327. if ourIP4 == nil && ourIP6 == nil {
  328. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  329. "description": "cannot detect public IP address",
  330. "error": errors.New("cannot detect automatically and public-ipv4/public-ipv6 are not set in config"),
  331. })
  332. return false
  333. }
  334. strAddresses := []string{}
  335. for _, value := range addresses {
  336. if (ourIP4 != nil && value.IP.String() == ourIP4.String()) ||
  337. (ourIP6 != nil && value.IP.String() == ourIP6.String()) {
  338. tplODNSSNIMatch.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  339. "ip": value.IP,
  340. "hostname": d.conf.Secret.Host,
  341. })
  342. return true
  343. }
  344. strAddresses = append(strAddresses, `"`+value.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": ourIP4,
  350. "ip6": ourIP6,
  351. })
  352. return false
  353. }