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
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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