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
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

doctor.go 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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": "host",
  119. "new_section": "domain-fronting",
  120. })
  121. }
  122. if d.conf.DomainFronting.IP.Value != nil {
  123. ok = false
  124. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  125. "when": "2.4.0",
  126. "old": "ip",
  127. "old_section": "domain-fronting",
  128. "new": "host",
  129. "new_section": "domain-fronting",
  130. })
  131. }
  132. if d.conf.DomainFrontingPort.Value != 0 {
  133. ok = false
  134. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  135. "when": "2.3.0",
  136. "old": "domain-fronting-port",
  137. "old_section": "",
  138. "new": "port",
  139. "new_section": "domain-fronting",
  140. })
  141. }
  142. if d.conf.DomainFrontingProxyProtocol.Value {
  143. ok = false
  144. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  145. "when": "2.3.0",
  146. "old": "domain-fronting-proxy-protocol",
  147. "old_section": "",
  148. "new": "proxy-protocol",
  149. "new_section": "domain-fronting",
  150. })
  151. }
  152. if d.conf.Network.DOHIP.Value != nil {
  153. ok = false
  154. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  155. "when": "2.3.0",
  156. "old": "doh-ip",
  157. "old_section": "network",
  158. "new": "dns",
  159. "new_section": "network",
  160. })
  161. }
  162. if ok {
  163. fmt.Println(" ✅ All good")
  164. }
  165. return ok
  166. }
  167. func (d *Doctor) checkTimeSkewness() bool {
  168. response, err := ntp.Query("0.pool.ntp.org")
  169. if err != nil {
  170. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  171. "description": "cannot access ntp pool",
  172. "error": err,
  173. })
  174. return false
  175. }
  176. skewness := response.ClockOffset.Abs()
  177. confValue := d.conf.TolerateTimeSkewness.Get(mtglib.DefaultTolerateTimeSkewness)
  178. diff := float64(skewness) / float64(confValue)
  179. tplData := map[string]any{
  180. "drift": response.ClockOffset,
  181. "value": confValue,
  182. }
  183. switch {
  184. case diff < 0.3:
  185. tplOTimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  186. return true
  187. case diff < 0.7:
  188. tplWTimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  189. default:
  190. tplETimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  191. }
  192. return false
  193. }
  194. func (d *Doctor) checkNetwork(ntw mtglib.Network) bool {
  195. dcs := slices.Collect(maps.Keys(essentials.TelegramCoreAddresses))
  196. slices.Sort(dcs)
  197. ok := true
  198. for _, dc := range dcs {
  199. err := d.checkNetworkAddresses(ntw, essentials.TelegramCoreAddresses[dc])
  200. if err == nil {
  201. tplODCConnect.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  202. "dc": dc,
  203. })
  204. } else {
  205. tplEDCConnect.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  206. "dc": dc,
  207. "error": err,
  208. })
  209. ok = false
  210. }
  211. }
  212. return ok
  213. }
  214. func (d *Doctor) checkNetworkAddresses(ntw mtglib.Network, addresses []string) error {
  215. checkAddresses := []string{}
  216. switch d.conf.PreferIP.Get("prefer-ip4") {
  217. case "only-ipv4":
  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. case "only-ipv6":
  228. for _, addr := range addresses {
  229. host, _, err := net.SplitHostPort(addr)
  230. if err != nil {
  231. panic(err)
  232. }
  233. if ip := net.ParseIP(host); ip != nil && ip.To4() == nil {
  234. checkAddresses = append(checkAddresses, addr)
  235. }
  236. }
  237. default:
  238. checkAddresses = addresses
  239. }
  240. if len(checkAddresses) == 0 {
  241. return fmt.Errorf("no suitable addresses after IP version filtering")
  242. }
  243. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  244. defer cancel()
  245. var (
  246. conn net.Conn
  247. err error
  248. )
  249. for _, addr := range checkAddresses {
  250. conn, err = ntw.DialContext(ctx, "tcp", addr)
  251. if err != nil {
  252. continue
  253. }
  254. conn.Close() //nolint: errcheck
  255. return nil
  256. }
  257. return err
  258. }
  259. func (d *Doctor) checkFrontingDomain(ntw mtglib.Network) bool {
  260. host := d.conf.Secret.Host
  261. if override := d.conf.GetDomainFrontingHost(); override != "" {
  262. host = override
  263. }
  264. port := d.conf.GetDomainFrontingPort(mtglib.DefaultDomainFrontingPort)
  265. address := net.JoinHostPort(host, strconv.Itoa(int(port)))
  266. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  267. defer cancel()
  268. dialer := ntw.NativeDialer()
  269. conn, err := dialer.DialContext(ctx, "tcp", address)
  270. if err != nil {
  271. tplEFrontingDomain.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  272. "address": address,
  273. "error": err,
  274. })
  275. return false
  276. }
  277. conn.Close() //nolint: errcheck
  278. tplOFrontingDomain.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  279. "address": address,
  280. })
  281. return true
  282. }
  283. func (d *Doctor) checkSecretHost(resolver *net.Resolver, ntw mtglib.Network) bool {
  284. addresses, err := resolver.LookupIPAddr(context.Background(), d.conf.Secret.Host)
  285. if err != nil {
  286. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  287. "description": fmt.Sprintf("cannot resolve DNS name of %s", d.conf.Secret.Host),
  288. "error": err,
  289. })
  290. return false
  291. }
  292. ourIP4 := d.conf.PublicIPv4.Get(nil)
  293. if ourIP4 == nil {
  294. ourIP4 = getIP(ntw, "tcp4")
  295. }
  296. ourIP6 := d.conf.PublicIPv6.Get(nil)
  297. if ourIP6 == nil {
  298. ourIP6 = getIP(ntw, "tcp6")
  299. }
  300. if ourIP4 == nil && ourIP6 == nil {
  301. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  302. "description": "cannot detect public IP address",
  303. "error": errors.New("cannot detect automatically and public-ipv4/public-ipv6 are not set in config"),
  304. })
  305. return false
  306. }
  307. strAddresses := []string{}
  308. for _, value := range addresses {
  309. if (ourIP4 != nil && value.IP.String() == ourIP4.String()) ||
  310. (ourIP6 != nil && value.IP.String() == ourIP6.String()) {
  311. tplODNSSNIMatch.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  312. "ip": value.IP,
  313. "hostname": d.conf.Secret.Host,
  314. })
  315. return true
  316. }
  317. strAddresses = append(strAddresses, `"`+value.IP.String()+`"`)
  318. }
  319. tplEDNSSNIMatch.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  320. "hostname": d.conf.Secret.Host,
  321. "resolved": strings.Join(strAddresses, ", "),
  322. "ip4": ourIP4,
  323. "ip6": ourIP6,
  324. })
  325. return false
  326. }