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

utils.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package cli
  2. import (
  3. "context"
  4. "io"
  5. "net"
  6. "net/http"
  7. "strings"
  8. "github.com/9seconds/mtg/v2/essentials"
  9. "github.com/9seconds/mtg/v2/internal/config"
  10. "github.com/9seconds/mtg/v2/mtglib"
  11. )
  12. // defaultPublicIPEndpoints is the fallback used when network.public-ip-endpoints
  13. // is not set in config. Each endpoint must return the client's public IP as a
  14. // single address in the plain-text response body.
  15. var defaultPublicIPEndpoints = []string{
  16. "https://ifconfig.co",
  17. "https://icanhazip.com",
  18. "https://ifconfig.me",
  19. }
  20. // resolvePublicIPEndpoints returns the configured endpoint list, falling back
  21. // to defaultPublicIPEndpoints when none are configured.
  22. func resolvePublicIPEndpoints(configured []config.TypeHttpsURL) []string {
  23. if len(configured) == 0 {
  24. return defaultPublicIPEndpoints
  25. }
  26. out := make([]string, 0, len(configured))
  27. for _, u := range configured {
  28. if v := u.Get(nil); v != nil {
  29. out = append(out, v.String())
  30. }
  31. }
  32. if len(out) == 0 {
  33. return defaultPublicIPEndpoints
  34. }
  35. return out
  36. }
  37. func getIP(ctx context.Context, ntw mtglib.Network, protocol string, endpoints []string) net.IP {
  38. dialer := ntw.NativeDialer()
  39. client := ntw.MakeHTTPClient(func(ctx context.Context, network, address string) (essentials.Conn, error) {
  40. conn, err := dialer.DialContext(ctx, protocol, address)
  41. if err != nil {
  42. return nil, err
  43. }
  44. return essentials.WrapNetConn(conn), err
  45. })
  46. for _, endpoint := range endpoints {
  47. if ip := fetchPublicIP(ctx, client, endpoint); ip != nil {
  48. return ip
  49. }
  50. }
  51. return nil
  52. }
  53. func fetchPublicIP(ctx context.Context, client *http.Client, endpoint string) net.IP {
  54. req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
  55. if err != nil {
  56. return nil
  57. }
  58. req.Header.Set("Accept", "text/plain")
  59. req.Header.Set("User-Agent", "curl/8")
  60. resp, err := client.Do(req)
  61. if err != nil {
  62. return nil
  63. }
  64. defer func() {
  65. io.Copy(io.Discard, resp.Body) //nolint: errcheck
  66. resp.Body.Close() //nolint: errcheck
  67. }()
  68. if resp.StatusCode != http.StatusOK {
  69. return nil
  70. }
  71. data, err := io.ReadAll(resp.Body)
  72. if err != nil {
  73. return nil
  74. }
  75. return net.ParseIP(strings.TrimSpace(string(data)))
  76. }