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文字以内のものにしてください。

doctor.go 7.9KB

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