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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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/network/v2"
  20. "github.com/beevik/ntp"
  21. )
  22. var (
  23. tplError = template.Must(
  24. template.New("").Parse(" ‼️ {{ .description }}: {{ .error }}\n"),
  25. )
  26. tplWDeprecatedConfig = template.Must(
  27. template.New("").
  28. 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"),
  29. )
  30. tplOTimeSkewness = template.Must(
  31. template.New("").
  32. Parse(" ✅ Time drift is {{ .drift }}, but tolerate-time-skewness is {{ .value }}\n"),
  33. )
  34. tplWTimeSkewness = template.Must(
  35. template.New("").
  36. Parse(" ⚠️ Time drift is {{ .drift }}, but tolerate-time-skewness is {{ .value }}. Please check ntp.\n"),
  37. )
  38. tplETimeSkewness = template.Must(
  39. template.New("").
  40. Parse(" ❌ Time drift is {{ .drift }}, but tolerate-time-skewness is {{ .value }}. You will get many rejected connections!\n"),
  41. )
  42. tplODCConnect = template.Must(
  43. template.New("").Parse(" ✅ DC {{ .dc }}\n"),
  44. )
  45. tplEDCConnect = template.Must(
  46. template.New("").Parse(" ❌ DC {{ .dc }}: {{ .error }}\n"),
  47. )
  48. tplODNSSNIMatch = template.Must(
  49. template.New("").Parse(" ✅ IP address {{ .ip }} matches secret hostname {{ .hostname }}\n"),
  50. )
  51. tplEDNSSNIMatch = template.Must(
  52. 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"),
  53. )
  54. tplOFrontingDomain = template.Must(
  55. template.New("").Parse(" ✅ {{ .address }} is reachable\n"),
  56. )
  57. tplEFrontingDomain = template.Must(
  58. template.New("").Parse(" ❌ {{ .address }}: {{ .error }}\n"),
  59. )
  60. )
  61. type Doctor struct {
  62. conf *config.Config
  63. ConfigPath string `kong:"arg,required,type='existingfile',help='Path to the configuration file.',name='config-path'"` //nolint: lll
  64. 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
  65. }
  66. func (d *Doctor) Run(cli *CLI, version string) error {
  67. conf, err := utils.ReadConfig(d.ConfigPath)
  68. if err != nil {
  69. return fmt.Errorf("cannot init config: %w", err)
  70. }
  71. d.conf = conf
  72. fmt.Println("Deprecated options")
  73. everythingOK := d.checkDeprecatedConfig()
  74. fmt.Println("Time skewness")
  75. everythingOK = d.checkTimeSkewness() && everythingOK
  76. resolver, err := network.GetDNS(conf.GetDNS())
  77. if err != nil {
  78. return fmt.Errorf("cannot create DNS resolver: %w", err)
  79. }
  80. base := network.New(
  81. resolver,
  82. "",
  83. conf.Network.Timeout.TCP.Get(10*time.Second),
  84. conf.Network.Timeout.HTTP.Get(0),
  85. conf.Network.Timeout.Idle.Get(0),
  86. net.KeepAliveConfig{
  87. Enable: !conf.Network.KeepAlive.Disabled.Get(false),
  88. Idle: conf.Network.KeepAlive.Idle.Get(0),
  89. Interval: conf.Network.KeepAlive.Interval.Get(0),
  90. Count: int(conf.Network.KeepAlive.Count.Get(0)),
  91. },
  92. int(conf.Network.TCPNotSentLowat.Get(network.DefaultTCPNotSentLowat)),
  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. errs := make([]error, len(dcs))
  205. var wg sync.WaitGroup
  206. for i, dc := range dcs {
  207. wg.Go(func() {
  208. defer func() {
  209. if r := recover(); r != nil {
  210. errs[i] = fmt.Errorf("panic: %v", r)
  211. }
  212. }()
  213. errs[i] = d.checkNetworkAddresses(ntw, essentials.TelegramCoreAddresses[dc])
  214. })
  215. }
  216. wg.Wait()
  217. ok := true
  218. for i, dc := range dcs {
  219. if errs[i] == nil {
  220. tplODCConnect.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  221. "dc": dc,
  222. })
  223. } else {
  224. tplEDCConnect.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  225. "dc": dc,
  226. "error": errs[i],
  227. })
  228. ok = false
  229. }
  230. }
  231. return ok
  232. }
  233. func (d *Doctor) checkNetworkAddresses(ntw mtglib.Network, addresses []string) error {
  234. checkAddresses := []string{}
  235. switch d.conf.PreferIP.Get("prefer-ip4") {
  236. case "only-ipv4":
  237. for _, addr := range addresses {
  238. host, _, err := net.SplitHostPort(addr)
  239. if err != nil {
  240. panic(err)
  241. }
  242. if ip := net.ParseIP(host); ip != nil && ip.To4() != nil {
  243. checkAddresses = append(checkAddresses, addr)
  244. }
  245. }
  246. case "only-ipv6":
  247. for _, addr := range addresses {
  248. host, _, err := net.SplitHostPort(addr)
  249. if err != nil {
  250. panic(err)
  251. }
  252. if ip := net.ParseIP(host); ip != nil && ip.To4() == nil {
  253. checkAddresses = append(checkAddresses, addr)
  254. }
  255. }
  256. default:
  257. checkAddresses = addresses
  258. }
  259. if len(checkAddresses) == 0 {
  260. return fmt.Errorf("no suitable addresses after IP version filtering")
  261. }
  262. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  263. defer cancel()
  264. var (
  265. conn net.Conn
  266. err error
  267. )
  268. for _, addr := range checkAddresses {
  269. conn, err = ntw.DialContext(ctx, "tcp", addr)
  270. if err != nil {
  271. continue
  272. }
  273. conn.Close() //nolint: errcheck
  274. return nil
  275. }
  276. return err
  277. }
  278. func (d *Doctor) checkFrontingDomain(ntw mtglib.Network) bool {
  279. host := d.conf.Secret.Host
  280. if override := d.conf.GetDomainFrontingHost(); override != "" {
  281. host = override
  282. }
  283. port := d.conf.GetDomainFrontingPort(mtglib.DefaultDomainFrontingPort)
  284. address := net.JoinHostPort(host, strconv.Itoa(int(port)))
  285. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  286. defer cancel()
  287. dialer := ntw.NativeDialer()
  288. conn, err := dialer.DialContext(ctx, "tcp", address)
  289. if err != nil {
  290. tplEFrontingDomain.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  291. "address": address,
  292. "error": err,
  293. })
  294. return false
  295. }
  296. conn.Close() //nolint: errcheck
  297. tplOFrontingDomain.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  298. "address": address,
  299. })
  300. return true
  301. }
  302. func (d *Doctor) checkSecretHost(resolver *net.Resolver, ntw mtglib.Network) bool {
  303. addresses, err := resolver.LookupIPAddr(context.Background(), d.conf.Secret.Host)
  304. if err != nil {
  305. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  306. "description": fmt.Sprintf("cannot resolve DNS name of %s", d.conf.Secret.Host),
  307. "error": err,
  308. })
  309. return false
  310. }
  311. ourIP4 := d.conf.PublicIPv4.Get(nil)
  312. if ourIP4 == nil {
  313. ourIP4 = getIP(ntw, "tcp4")
  314. }
  315. ourIP6 := d.conf.PublicIPv6.Get(nil)
  316. if ourIP6 == nil {
  317. ourIP6 = getIP(ntw, "tcp6")
  318. }
  319. if ourIP4 == nil && ourIP6 == nil {
  320. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  321. "description": "cannot detect public IP address",
  322. "error": errors.New("cannot detect automatically and public-ipv4/public-ipv6 are not set in config"),
  323. })
  324. return false
  325. }
  326. strAddresses := []string{}
  327. for _, value := range addresses {
  328. if (ourIP4 != nil && value.IP.String() == ourIP4.String()) ||
  329. (ourIP6 != nil && value.IP.String() == ourIP6.String()) {
  330. tplODNSSNIMatch.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  331. "ip": value.IP,
  332. "hostname": d.conf.Secret.Host,
  333. })
  334. return true
  335. }
  336. strAddresses = append(strAddresses, `"`+value.IP.String()+`"`)
  337. }
  338. tplEDNSSNIMatch.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  339. "hostname": d.conf.Secret.Host,
  340. "resolved": strings.Join(strAddresses, ", "),
  341. "ip4": ourIP4,
  342. "ip6": ourIP6,
  343. })
  344. return false
  345. }