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 символов.

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