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 10.0KB

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