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

base.go 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package cli
  2. import (
  3. "fmt"
  4. "net"
  5. "net/url"
  6. "os"
  7. "github.com/9seconds/mtg/v2/config"
  8. "github.com/9seconds/mtg/v2/mtglib"
  9. "github.com/9seconds/mtg/v2/network"
  10. )
  11. type base struct {
  12. ConfigPath string `kong:"arg,required,type='existingfile',help='Path to the configuration file.',name='config-path'"` // nolint: lll
  13. Network mtglib.Network `kong:"-"`
  14. Config *config.Config `kong:"-"`
  15. }
  16. func (b *base) ReadConfig(version string) error {
  17. content, err := os.ReadFile(b.ConfigPath)
  18. if err != nil {
  19. return fmt.Errorf("cannot read config file: %w", err)
  20. }
  21. conf, err := config.Parse(content)
  22. if err != nil {
  23. return fmt.Errorf("cannot parse config: %w", err)
  24. }
  25. ntw, err := b.makeNetwork(conf, version)
  26. if err != nil {
  27. return fmt.Errorf("cannot build a network: %w", err)
  28. }
  29. b.Config = conf
  30. b.Network = ntw
  31. return nil
  32. }
  33. func (b *base) makeNetwork(conf *config.Config, version string) (mtglib.Network, error) {
  34. tcpTimeout := conf.Network.Timeout.TCP.Value(network.DefaultTimeout)
  35. httpTimeout := conf.Network.Timeout.HTTP.Value(network.DefaultHTTPTimeout)
  36. dohIP := conf.Network.DOHIP.Value(net.ParseIP(network.DefaultDOHHostname)).String()
  37. bufferSize := conf.TCPBuffer.Value(network.DefaultBufferSize)
  38. userAgent := "mtg/" + version
  39. baseDialer, err := network.NewDefaultDialer(tcpTimeout, int(bufferSize))
  40. if err != nil {
  41. return nil, fmt.Errorf("cannot build a default dialer: %w", err)
  42. }
  43. proxyURLs := make([]*url.URL, 0, len(conf.Network.Proxies))
  44. for _, v := range conf.Network.Proxies {
  45. if value := v.Value(nil); value != nil {
  46. proxyURLs = append(proxyURLs, v.Value(nil))
  47. }
  48. }
  49. switch len(proxyURLs) {
  50. case 0:
  51. return network.NewNetwork(baseDialer, userAgent, dohIP, httpTimeout)
  52. case 1:
  53. socksDialer, err := network.NewSocks5Dialer(baseDialer, proxyURLs[0])
  54. if err != nil {
  55. return nil, fmt.Errorf("cannot build socks5 dialer: %w", err)
  56. }
  57. return network.NewNetwork(socksDialer, userAgent, dohIP, httpTimeout)
  58. }
  59. socksDialer, err := network.NewLoadBalancedSocks5Dialer(baseDialer, proxyURLs)
  60. if err != nil {
  61. return nil, fmt.Errorf("cannot build socks5 dialer: %w", err)
  62. }
  63. return network.NewNetwork(socksDialer, userAgent, dohIP, httpTimeout)
  64. }