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

public_config_updater.go 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package dc
  2. import (
  3. "bufio"
  4. "context"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "regexp"
  9. "strconv"
  10. )
  11. var publicConfigRe = regexp.MustCompile(`^\s*proxy_for\s+(\d+)\s+(\S+?)?;\s*$`)
  12. type PublicConfigUpdater struct {
  13. updater
  14. http *http.Client
  15. tg *Telegram
  16. }
  17. func (p *PublicConfigUpdater) Run(ctx context.Context, url, network string) {
  18. p.run(ctx, func() error {
  19. req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
  20. if err != nil {
  21. panic(err)
  22. }
  23. resp, err := p.http.Do(req)
  24. if err != nil {
  25. if resp != nil {
  26. io.Copy(io.Discard, resp.Body) //nolint: errcheck
  27. resp.Body.Close() //nolint: errcheck
  28. }
  29. return fmt.Errorf("cannot fetch url %s: %w", url, err)
  30. }
  31. if resp.StatusCode >= http.StatusBadRequest {
  32. return fmt.Errorf("unexpected status code from %s: %d", url, resp.StatusCode)
  33. }
  34. scanner := bufio.NewScanner(resp.Body)
  35. addrs := map[int][]Addr{}
  36. for scanner.Scan() {
  37. matches := publicConfigRe.FindStringSubmatch(scanner.Text())
  38. if len(matches) != 3 {
  39. continue
  40. }
  41. dc, err := strconv.Atoi(matches[1])
  42. if err != nil {
  43. continue
  44. }
  45. switch dc {
  46. // this is a list of DC we currently support. Other are ignored.
  47. case 203: // CDN DC
  48. p.logger.Info(fmt.Sprintf("found %s address for DC %d", matches[2], dc))
  49. addrs[dc] = append(addrs[dc], Addr{
  50. Network: network,
  51. Address: matches[2],
  52. })
  53. }
  54. }
  55. if err := scanner.Err(); err != nil {
  56. return fmt.Errorf("cannot read response body from %s: %w", url, err)
  57. }
  58. p.tg.lock.Lock()
  59. defer p.tg.lock.Unlock()
  60. if network == "tcp4" {
  61. p.tg.view.publicConfigs.v4 = addrs
  62. } else {
  63. p.tg.view.publicConfigs.v6 = addrs
  64. }
  65. return nil
  66. })
  67. }
  68. func NewPublicConfigUpdater(tg *Telegram, logger Logger, client *http.Client) *PublicConfigUpdater {
  69. return &PublicConfigUpdater{
  70. updater: updater{
  71. logger: logger,
  72. period: PublicConfigUpdateEach,
  73. },
  74. http: client,
  75. tg: tg,
  76. }
  77. }