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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. package cli
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "maps"
  7. "net"
  8. "os"
  9. "slices"
  10. "strings"
  11. "text/template"
  12. "time"
  13. "github.com/9seconds/mtg/v2/essentials"
  14. "github.com/9seconds/mtg/v2/internal/config"
  15. "github.com/9seconds/mtg/v2/internal/utils"
  16. "github.com/9seconds/mtg/v2/mtglib"
  17. "github.com/9seconds/mtg/v2/network/v2"
  18. "github.com/beevik/ntp"
  19. )
  20. var (
  21. tplError = template.Must(
  22. template.New("").Parse(" ‼️ {{ .description }}: {{ .error }}\n"),
  23. )
  24. tplWDeprecatedConfig = template.Must(
  25. template.New("").
  26. 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"),
  27. )
  28. tplOTimeSkewness = template.Must(
  29. template.New("").
  30. Parse(" ✅ Time drift is {{ .drift }}, but tolerate-time-skewness is {{ .value }}\n"),
  31. )
  32. tplWTimeSkewness = template.Must(
  33. template.New("").
  34. Parse(" ⚠️ Time drift is {{ .drift }}, but tolerate-time-skewness is {{ .value }}. Please check ntp.\n"),
  35. )
  36. tplETimeSkewness = template.Must(
  37. template.New("").
  38. Parse(" ❌ Time drift is {{ .drift }}, but tolerate-time-skewness is {{ .value }}. You will get many rejected connections!\n"),
  39. )
  40. tplODCConnect = template.Must(
  41. template.New("").Parse(" ✅ DC {{ .dc }}\n"),
  42. )
  43. tplEDCConnect = template.Must(
  44. template.New("").Parse(" ❌ DC {{ .dc }}: {{ .error }}\n"),
  45. )
  46. tplODNSSNIMatch = template.Must(
  47. template.New("").Parse(" ✅ IP address {{ .ip }} matches secret hostname {{ .hostname }}\n"),
  48. )
  49. tplEDNSSNIMatch = template.Must(
  50. 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"),
  51. )
  52. )
  53. type Doctor struct {
  54. conf *config.Config
  55. ConfigPath string `kong:"arg,required,type='existingfile',help='Path to the configuration file.',name='config-path'"` //nolint: lll
  56. }
  57. func (d *Doctor) Run(cli *CLI, version string) error {
  58. conf, err := utils.ReadConfig(d.ConfigPath)
  59. if err != nil {
  60. return fmt.Errorf("cannot init config: %w", err)
  61. }
  62. d.conf = conf
  63. fmt.Println("Deprecated options")
  64. everythingOK := d.checkDeprecatedConfig()
  65. fmt.Println("Time skewness")
  66. everythingOK = d.checkTimeSkewness() && everythingOK
  67. resolver, err := network.GetDNS(conf.GetDNS())
  68. if err != nil {
  69. return fmt.Errorf("cannot create DNS resolver: %w", err)
  70. }
  71. base := network.New(
  72. resolver,
  73. "",
  74. conf.Network.Timeout.TCP.Get(10*time.Second),
  75. conf.Network.Timeout.HTTP.Get(0),
  76. conf.Network.Timeout.Idle.Get(0),
  77. )
  78. fmt.Println("Validate native network connectivity")
  79. everythingOK = d.checkNetwork(base) && everythingOK
  80. for _, url := range conf.Network.Proxies {
  81. value, err := network.NewProxyNetwork(base, url.Get(nil))
  82. if err != nil {
  83. return err
  84. }
  85. fmt.Printf("Validate network connectivity with proxy %s\n", url.Get(nil))
  86. everythingOK = d.checkNetwork(value) && everythingOK
  87. }
  88. fmt.Println("Validate SNI-DNS match")
  89. everythingOK = d.checkSecretHost(resolver, base) && everythingOK
  90. if !everythingOK {
  91. os.Exit(1)
  92. }
  93. return nil
  94. }
  95. func (d *Doctor) checkDeprecatedConfig() bool {
  96. ok := true
  97. if d.conf.DomainFrontingIP.Value != nil {
  98. ok = false
  99. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  100. "when": "2.3.0",
  101. "old": "domain-fronting-ip",
  102. "old_section": "",
  103. "new": "ip",
  104. "new_section": "domain-fronting",
  105. })
  106. }
  107. if d.conf.DomainFrontingPort.Value != 0 {
  108. ok = false
  109. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  110. "when": "2.3.0",
  111. "old": "domain-fronting-port",
  112. "old_section": "",
  113. "new": "port",
  114. "new_section": "domain-fronting",
  115. })
  116. }
  117. if d.conf.DomainFrontingProxyProtocol.Value {
  118. ok = false
  119. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  120. "when": "2.3.0",
  121. "old": "domain-fronting-proxy-protocol",
  122. "old_section": "",
  123. "new": "proxy-protocol",
  124. "new_section": "domain-fronting",
  125. })
  126. }
  127. if d.conf.Network.DOHIP.Value != nil {
  128. ok = false
  129. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  130. "when": "2.3.0",
  131. "old": "doh-ip",
  132. "old_section": "network",
  133. "new": "dns",
  134. "new_section": "network",
  135. })
  136. }
  137. if ok {
  138. fmt.Println(" ✅ All good")
  139. }
  140. return ok
  141. }
  142. func (d *Doctor) checkTimeSkewness() bool {
  143. response, err := ntp.Query("0.pool.ntp.org")
  144. if err != nil {
  145. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  146. "description": "cannot access ntp pool",
  147. "error": err,
  148. })
  149. return false
  150. }
  151. skewness := response.ClockOffset.Abs()
  152. confValue := d.conf.TolerateTimeSkewness.Get(mtglib.DefaultTolerateTimeSkewness)
  153. diff := float64(skewness) / float64(confValue)
  154. tplData := map[string]any{
  155. "drift": response.ClockOffset,
  156. "value": confValue,
  157. }
  158. switch {
  159. case diff < 0.3:
  160. tplOTimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  161. return true
  162. case diff < 0.7:
  163. tplWTimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  164. default:
  165. tplETimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  166. }
  167. return false
  168. }
  169. func (d *Doctor) checkNetwork(ntw mtglib.Network) bool {
  170. dcs := slices.Collect(maps.Keys(essentials.TelegramCoreAddresses))
  171. slices.Sort(dcs)
  172. ok := true
  173. for _, dc := range dcs {
  174. err := d.checkNetworkAddresses(ntw, essentials.TelegramCoreAddresses[dc])
  175. if err == nil {
  176. tplODCConnect.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  177. "dc": dc,
  178. })
  179. } else {
  180. tplEDCConnect.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  181. "dc": dc,
  182. "error": err,
  183. })
  184. ok = false
  185. }
  186. }
  187. return ok
  188. }
  189. func (d *Doctor) checkNetworkAddresses(ntw mtglib.Network, addresses []string) error {
  190. checkAddresses := []string{}
  191. switch d.conf.PreferIP.Get("prefer-ip4") {
  192. case "only-ipv4":
  193. for _, addr := range addresses {
  194. host, _, err := net.SplitHostPort(addr)
  195. if err != nil {
  196. panic(err)
  197. }
  198. if ip := net.ParseIP(host); ip != nil && ip.To4() != nil {
  199. checkAddresses = append(checkAddresses, addr)
  200. }
  201. }
  202. case "only-ipv6":
  203. for _, addr := range addresses {
  204. host, _, err := net.SplitHostPort(addr)
  205. if err != nil {
  206. panic(err)
  207. }
  208. if ip := net.ParseIP(host); ip != nil && ip.To4() == nil {
  209. checkAddresses = append(checkAddresses, addr)
  210. }
  211. }
  212. default:
  213. checkAddresses = addresses
  214. }
  215. if len(checkAddresses) == 0 {
  216. return fmt.Errorf("no suitable addresses after IP version filtering")
  217. }
  218. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  219. defer cancel()
  220. var (
  221. conn net.Conn
  222. err error
  223. )
  224. for _, addr := range checkAddresses {
  225. conn, err = ntw.DialContext(ctx, "tcp", addr)
  226. if err != nil {
  227. continue
  228. }
  229. conn.Close() //nolint: errcheck
  230. return nil
  231. }
  232. return err
  233. }
  234. func (d *Doctor) checkSecretHost(resolver *net.Resolver, ntw mtglib.Network) bool {
  235. addresses, err := resolver.LookupIPAddr(context.Background(), d.conf.Secret.Host)
  236. if err != nil {
  237. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  238. "description": fmt.Sprintf("cannot resolve DNS name of %s", d.conf.Secret.Host),
  239. "error": err,
  240. })
  241. return false
  242. }
  243. ourIP4 := getIP(ntw, "tcp4")
  244. ourIP6 := getIP(ntw, "tcp6")
  245. if ourIP4 == nil && ourIP6 == nil {
  246. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  247. "description": "cannot detect public IP address",
  248. "error": errors.New("ifconfig.co is unreachable for both IPv4 and IPv6"),
  249. })
  250. return false
  251. }
  252. strAddresses := []string{}
  253. for _, value := range addresses {
  254. if (ourIP4 != nil && value.IP.String() == ourIP4.String()) ||
  255. (ourIP6 != nil && value.IP.String() == ourIP6.String()) {
  256. tplODNSSNIMatch.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  257. "ip": value.IP,
  258. "hostname": d.conf.Secret.Host,
  259. })
  260. return true
  261. }
  262. strAddresses = append(strAddresses, `"`+value.IP.String()+`"`)
  263. }
  264. tplEDNSSNIMatch.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  265. "hostname": d.conf.Secret.Host,
  266. "resolved": strings.Join(strAddresses, ", "),
  267. "ip4": ourIP4,
  268. "ip6": ourIP6,
  269. })
  270. return false
  271. }