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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. }
  64. func (d *Doctor) Run(cli *CLI, version string) error {
  65. conf, err := utils.ReadConfig(d.ConfigPath)
  66. if err != nil {
  67. return fmt.Errorf("cannot init config: %w", err)
  68. }
  69. d.conf = conf
  70. fmt.Println("Deprecated options")
  71. everythingOK := d.checkDeprecatedConfig()
  72. fmt.Println("Time skewness")
  73. everythingOK = d.checkTimeSkewness() && everythingOK
  74. resolver, err := network.GetDNS(conf.GetDNS())
  75. if err != nil {
  76. return fmt.Errorf("cannot create DNS resolver: %w", err)
  77. }
  78. base := network.New(
  79. resolver,
  80. "",
  81. conf.Network.Timeout.TCP.Get(10*time.Second),
  82. conf.Network.Timeout.HTTP.Get(0),
  83. conf.Network.Timeout.Idle.Get(0),
  84. net.KeepAliveConfig{
  85. Enable: !conf.Network.KeepAlive.Disabled.Get(false),
  86. Idle: conf.Network.KeepAlive.Idle.Get(0),
  87. Interval: conf.Network.KeepAlive.Interval.Get(0),
  88. Count: int(conf.Network.KeepAlive.Count.Get(0)),
  89. },
  90. )
  91. fmt.Println("Validate native network connectivity")
  92. everythingOK = d.checkNetwork(base) && everythingOK
  93. for _, url := range conf.Network.Proxies {
  94. value, err := network.NewProxyNetwork(base, url.Get(nil))
  95. if err != nil {
  96. return err
  97. }
  98. fmt.Printf("Validate network connectivity with proxy %s\n", url.Get(nil))
  99. everythingOK = d.checkNetwork(value) && everythingOK
  100. }
  101. fmt.Println("Validate fronting domain connectivity")
  102. everythingOK = d.checkFrontingDomain(base) && everythingOK
  103. fmt.Println("Validate SNI-DNS match")
  104. everythingOK = d.checkSecretHost(resolver, base) && everythingOK
  105. if !everythingOK {
  106. os.Exit(1)
  107. }
  108. return nil
  109. }
  110. func (d *Doctor) checkDeprecatedConfig() bool {
  111. ok := true
  112. if d.conf.DomainFrontingIP.Value != nil {
  113. ok = false
  114. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  115. "when": "2.3.0",
  116. "old": "domain-fronting-ip",
  117. "old_section": "",
  118. "new": "ip",
  119. "new_section": "domain-fronting",
  120. })
  121. }
  122. if d.conf.DomainFrontingPort.Value != 0 {
  123. ok = false
  124. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  125. "when": "2.3.0",
  126. "old": "domain-fronting-port",
  127. "old_section": "",
  128. "new": "port",
  129. "new_section": "domain-fronting",
  130. })
  131. }
  132. if d.conf.DomainFrontingProxyProtocol.Value {
  133. ok = false
  134. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  135. "when": "2.3.0",
  136. "old": "domain-fronting-proxy-protocol",
  137. "old_section": "",
  138. "new": "proxy-protocol",
  139. "new_section": "domain-fronting",
  140. })
  141. }
  142. if d.conf.Network.DOHIP.Value != nil {
  143. ok = false
  144. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  145. "when": "2.3.0",
  146. "old": "doh-ip",
  147. "old_section": "network",
  148. "new": "dns",
  149. "new_section": "network",
  150. })
  151. }
  152. if ok {
  153. fmt.Println(" ✅ All good")
  154. }
  155. return ok
  156. }
  157. func (d *Doctor) checkTimeSkewness() bool {
  158. response, err := ntp.Query("0.pool.ntp.org")
  159. if err != nil {
  160. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  161. "description": "cannot access ntp pool",
  162. "error": err,
  163. })
  164. return false
  165. }
  166. skewness := response.ClockOffset.Abs()
  167. confValue := d.conf.TolerateTimeSkewness.Get(mtglib.DefaultTolerateTimeSkewness)
  168. diff := float64(skewness) / float64(confValue)
  169. tplData := map[string]any{
  170. "drift": response.ClockOffset,
  171. "value": confValue,
  172. }
  173. switch {
  174. case diff < 0.3:
  175. tplOTimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  176. return true
  177. case diff < 0.7:
  178. tplWTimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  179. default:
  180. tplETimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  181. }
  182. return false
  183. }
  184. func (d *Doctor) checkNetwork(ntw mtglib.Network) bool {
  185. dcs := slices.Collect(maps.Keys(essentials.TelegramCoreAddresses))
  186. slices.Sort(dcs)
  187. ok := true
  188. for _, dc := range dcs {
  189. err := d.checkNetworkAddresses(ntw, essentials.TelegramCoreAddresses[dc])
  190. if err == nil {
  191. tplODCConnect.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  192. "dc": dc,
  193. })
  194. } else {
  195. tplEDCConnect.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  196. "dc": dc,
  197. "error": err,
  198. })
  199. ok = false
  200. }
  201. }
  202. return ok
  203. }
  204. func (d *Doctor) checkNetworkAddresses(ntw mtglib.Network, addresses []string) error {
  205. checkAddresses := []string{}
  206. switch d.conf.PreferIP.Get("prefer-ip4") {
  207. case "only-ipv4":
  208. for _, addr := range addresses {
  209. host, _, err := net.SplitHostPort(addr)
  210. if err != nil {
  211. panic(err)
  212. }
  213. if ip := net.ParseIP(host); ip != nil && ip.To4() != nil {
  214. checkAddresses = append(checkAddresses, addr)
  215. }
  216. }
  217. case "only-ipv6":
  218. for _, addr := range addresses {
  219. host, _, err := net.SplitHostPort(addr)
  220. if err != nil {
  221. panic(err)
  222. }
  223. if ip := net.ParseIP(host); ip != nil && ip.To4() == nil {
  224. checkAddresses = append(checkAddresses, addr)
  225. }
  226. }
  227. default:
  228. checkAddresses = addresses
  229. }
  230. if len(checkAddresses) == 0 {
  231. return fmt.Errorf("no suitable addresses after IP version filtering")
  232. }
  233. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  234. defer cancel()
  235. var (
  236. conn net.Conn
  237. err error
  238. )
  239. for _, addr := range checkAddresses {
  240. conn, err = ntw.DialContext(ctx, "tcp", addr)
  241. if err != nil {
  242. continue
  243. }
  244. conn.Close() //nolint: errcheck
  245. return nil
  246. }
  247. return err
  248. }
  249. func (d *Doctor) checkFrontingDomain(ntw mtglib.Network) bool {
  250. host := d.conf.Secret.Host
  251. if ip := d.conf.GetDomainFrontingIP(nil); ip != "" {
  252. host = ip
  253. }
  254. port := d.conf.GetDomainFrontingPort(mtglib.DefaultDomainFrontingPort)
  255. address := net.JoinHostPort(host, strconv.Itoa(int(port)))
  256. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  257. defer cancel()
  258. dialer := ntw.NativeDialer()
  259. conn, err := dialer.DialContext(ctx, "tcp", address)
  260. if err != nil {
  261. tplEFrontingDomain.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  262. "address": address,
  263. "error": err,
  264. })
  265. return false
  266. }
  267. conn.Close() //nolint: errcheck
  268. tplOFrontingDomain.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  269. "address": address,
  270. })
  271. return true
  272. }
  273. func (d *Doctor) checkSecretHost(resolver *net.Resolver, ntw mtglib.Network) bool {
  274. addresses, err := resolver.LookupIPAddr(context.Background(), d.conf.Secret.Host)
  275. if err != nil {
  276. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  277. "description": fmt.Sprintf("cannot resolve DNS name of %s", d.conf.Secret.Host),
  278. "error": err,
  279. })
  280. return false
  281. }
  282. ourIP4 := d.conf.PublicIPv4.Get(nil)
  283. if ourIP4 == nil {
  284. ourIP4 = getIP(ntw, "tcp4")
  285. }
  286. ourIP6 := d.conf.PublicIPv6.Get(nil)
  287. if ourIP6 == nil {
  288. ourIP6 = getIP(ntw, "tcp6")
  289. }
  290. if ourIP4 == nil && ourIP6 == nil {
  291. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  292. "description": "cannot detect public IP address",
  293. "error": errors.New("cannot detect automatically and public-ipv4/public-ipv6 are not set in config"),
  294. })
  295. return false
  296. }
  297. strAddresses := []string{}
  298. for _, value := range addresses {
  299. if (ourIP4 != nil && value.IP.String() == ourIP4.String()) ||
  300. (ourIP6 != nil && value.IP.String() == ourIP6.String()) {
  301. tplODNSSNIMatch.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  302. "ip": value.IP,
  303. "hostname": d.conf.Secret.Host,
  304. })
  305. return true
  306. }
  307. strAddresses = append(strAddresses, `"`+value.IP.String()+`"`)
  308. }
  309. tplEDNSSNIMatch.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  310. "hostname": d.conf.Secret.Host,
  311. "resolved": strings.Join(strAddresses, ", "),
  312. "ip4": ourIP4,
  313. "ip6": ourIP6,
  314. })
  315. return false
  316. }