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 1.9KB

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