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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net"
  8. "net/url"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/9seconds/mtg/v2/mtglib"
  14. "github.com/alecthomas/units"
  15. "github.com/pelletier/go-toml"
  16. )
  17. type configTypeHostPort struct {
  18. host configTypeIP
  19. port configTypePort
  20. }
  21. func (c *configTypeHostPort) UnmarshalText(data []byte) error {
  22. if len(data) == 0 {
  23. return nil
  24. }
  25. host, port, err := net.SplitHostPort(string(data))
  26. if err != nil {
  27. return fmt.Errorf("incorrect host:port syntax: %w", err)
  28. }
  29. if err := c.port.UnmarshalJSON([]byte(port)); err != nil {
  30. return fmt.Errorf("incorrect port in host:port: %w", err)
  31. }
  32. if err := c.host.UnmarshalText([]byte(host)); err != nil {
  33. return fmt.Errorf("incorrect host: %w", err)
  34. }
  35. return nil
  36. }
  37. func (c configTypeHostPort) String() string {
  38. return c.Value(net.IP{}, 0)
  39. }
  40. func (c configTypeHostPort) Value(defaultHostValue net.IP, defaultPortValue uint) string {
  41. return net.JoinHostPort(c.host.Value(defaultHostValue).String(),
  42. strconv.Itoa(int(c.port.Value(defaultPortValue))))
  43. }
  44. type configTypePort struct {
  45. value uint
  46. }
  47. func (c *configTypePort) UnmarshalJSON(data []byte) error {
  48. if len(data) == 0 {
  49. return nil
  50. }
  51. intValue, err := strconv.ParseUint(string(data), 10, 16)
  52. if err != nil {
  53. return fmt.Errorf("port number is not a number: %w", err)
  54. }
  55. if intValue == 0 || intValue > 65536 {
  56. return fmt.Errorf("port number should be 0 < portNo < 65536: %d", intValue)
  57. }
  58. c.value = uint(intValue)
  59. return nil
  60. }
  61. func (c configTypePort) String() string {
  62. return strconv.Itoa(int(c.value))
  63. }
  64. func (c configTypePort) Value(defaultValue uint) uint {
  65. if c.value == 0 {
  66. return defaultValue
  67. }
  68. return c.value
  69. }
  70. type configTypeBytes struct {
  71. value uint
  72. }
  73. func (c *configTypeBytes) UnmarshalText(data []byte) error {
  74. if len(data) == 0 {
  75. return nil
  76. }
  77. value, err := units.ParseStrictBytes(strings.ToUpper(string(data)))
  78. if err != nil {
  79. return fmt.Errorf("incorrect bytes value: %w", err)
  80. }
  81. if value < 0 {
  82. return fmt.Errorf("%d should be positive number", value)
  83. }
  84. c.value = uint(value)
  85. return nil
  86. }
  87. func (c configTypeBytes) String() string {
  88. return units.ToString(int64(c.value), 1024, "ib", "b")
  89. }
  90. func (c configTypeBytes) Value(defaultValue uint) uint {
  91. if c.value == 0 {
  92. return defaultValue
  93. }
  94. return c.value
  95. }
  96. type configTypePreferIP struct {
  97. value string
  98. }
  99. func (c *configTypePreferIP) UnmarshalText(data []byte) error {
  100. if len(data) == 0 {
  101. return nil
  102. }
  103. text := strings.ToLower(string(data))
  104. switch text {
  105. case "prefer-ipv4", "prefer-ipv6", "only-ipv4", "only-ipv6":
  106. c.value = text
  107. default:
  108. return fmt.Errorf("incorrect prefer-ip value: %s", string(data))
  109. }
  110. return nil
  111. }
  112. func (c *configTypePreferIP) String() string {
  113. return c.value
  114. }
  115. func (c *configTypePreferIP) Value(defaultValue string) string {
  116. if c.value == "" {
  117. return defaultValue
  118. }
  119. return c.value
  120. }
  121. type configTypeDuration struct {
  122. value time.Duration
  123. }
  124. func (c *configTypeDuration) UnmarshalText(data []byte) error {
  125. if len(data) == 0 {
  126. return nil
  127. }
  128. dur, err := time.ParseDuration(strings.ToLower(string(data)))
  129. if err != nil {
  130. return fmt.Errorf("incorrect duration: %w", err)
  131. }
  132. if dur < 0 {
  133. return fmt.Errorf("%s should be positive duration", dur)
  134. }
  135. c.value = dur
  136. return nil
  137. }
  138. func (c configTypeDuration) String() string {
  139. return c.value.String()
  140. }
  141. func (c configTypeDuration) Value(defaultValue time.Duration) time.Duration {
  142. if c.value == 0 {
  143. return defaultValue
  144. }
  145. return c.value
  146. }
  147. type configTypeFloat struct {
  148. value float64
  149. }
  150. func (c *configTypeFloat) UnmarshalJSON(data []byte) error {
  151. value, err := strconv.ParseFloat(string(data), 64)
  152. if err != nil {
  153. return fmt.Errorf("incorrect float value: %w", err)
  154. }
  155. if value < 0 {
  156. return fmt.Errorf("%f should be positive", value)
  157. }
  158. c.value = value
  159. return nil
  160. }
  161. func (c configTypeFloat) String() string {
  162. return strconv.FormatFloat(c.value, 'f', -1, 64)
  163. }
  164. func (c configTypeFloat) Value(defaultValue float64) float64 {
  165. if c.value < 0.00001 {
  166. return defaultValue
  167. }
  168. return c.value
  169. }
  170. type configTypeIP struct {
  171. value net.IP
  172. }
  173. func (c *configTypeIP) UnmarshalText(data []byte) error {
  174. if len(data) == 0 {
  175. return nil
  176. }
  177. ip := net.ParseIP(string(data))
  178. if ip == nil {
  179. return fmt.Errorf("incorrect ip address: %s", string(data))
  180. }
  181. c.value = ip
  182. return nil
  183. }
  184. func (c configTypeIP) String() string {
  185. return c.value.String()
  186. }
  187. func (c configTypeIP) Value(defaultValue net.IP) net.IP {
  188. if c.value == nil {
  189. return defaultValue
  190. }
  191. return c.value
  192. }
  193. type configTypeURL struct {
  194. value *url.URL
  195. }
  196. func (c *configTypeURL) UnmarshalText(data []byte) error {
  197. if len(data) == 0 {
  198. return nil
  199. }
  200. value, err := url.Parse(string(data))
  201. if err != nil {
  202. return fmt.Errorf("incorrect URL: %w", err)
  203. }
  204. c.value = value
  205. return nil
  206. }
  207. func (c configTypeURL) String() string {
  208. if c.value == nil {
  209. return ""
  210. }
  211. return c.value.String()
  212. }
  213. func (c configTypeURL) Value(defaultValue *url.URL) *url.URL {
  214. if c.value == nil {
  215. return defaultValue
  216. }
  217. return c.value
  218. }
  219. type configTypeMetricPrefix struct {
  220. value string
  221. }
  222. func (c *configTypeMetricPrefix) UnmarshalText(data []byte) error {
  223. if len(data) == 0 {
  224. return nil
  225. }
  226. prefix := string(data)
  227. if ok, err := regexp.MatchString("^[a-z0-9]+$", prefix); !ok || err != nil {
  228. return fmt.Errorf("incorrect metric prefix: %s", prefix)
  229. }
  230. c.value = prefix
  231. return nil
  232. }
  233. func (c configTypeMetricPrefix) String() string {
  234. return c.value
  235. }
  236. func (c configTypeMetricPrefix) Value(defaultValue string) string {
  237. if c.value == "" {
  238. return defaultValue
  239. }
  240. return c.value
  241. }
  242. type configTypeHTTPPath struct {
  243. value string
  244. }
  245. func (c *configTypeHTTPPath) UnmarshalText(data []byte) error { // nolint: unparam
  246. if len(data) > 0 {
  247. c.value = "/" + strings.Trim(string(data), "/")
  248. }
  249. return nil
  250. }
  251. func (c configTypeHTTPPath) String() string {
  252. return c.value
  253. }
  254. func (c configTypeHTTPPath) Value(defaultValue string) string {
  255. if c.value == "" {
  256. return defaultValue
  257. }
  258. return c.value
  259. }
  260. type config struct {
  261. Debug bool `json:"debug"`
  262. Secret mtglib.Secret `json:"secret"`
  263. BindTo configTypeHostPort `json:"bind-to"`
  264. TCPBuffer configTypeBytes `json:"tcp-buffer"`
  265. PreferIP configTypePreferIP `json:"prefer-ip"`
  266. CloakPort configTypePort `json:"cloak-port"`
  267. Probes struct {
  268. Time struct {
  269. Enabled bool `json:"enabled"`
  270. AllowSkewness configTypeDuration `json:"allow-skewness"`
  271. } `json:"time"`
  272. AntiReplay struct {
  273. Enabled bool `json:"enabled"`
  274. MaxSize configTypeBytes `json:"max-size"`
  275. ErrorRate configTypeFloat `json:"error-rate"`
  276. } `json:"anti-replay"`
  277. } `json:"probes"`
  278. Network struct {
  279. PublicIP struct {
  280. IPv4 configTypeIP `json:"ipv4"`
  281. IPv6 configTypeIP `json:"ipv6"`
  282. } `json:"public-ip"`
  283. DOHIP configTypeIP `json:"doh-ip"`
  284. Proxies []configTypeURL `json:"proxies"`
  285. } `json:"network"`
  286. Stats struct {
  287. StatsD struct {
  288. Enabled bool `json:"enabled"`
  289. Address configTypeHostPort `json:"address"`
  290. MetricPrefix configTypeMetricPrefix `json:"metric-prefix"`
  291. } `json:"statsd"`
  292. Prometheus struct {
  293. Enabled bool `json:"enabled"`
  294. BindTo configTypeHostPort `json:"bind-to"`
  295. HTTPPath configTypeHTTPPath `json:"http-path"`
  296. MetricPrefix configTypeMetricPrefix `json:"metric-prefix"`
  297. } `json:"prometheus"`
  298. } `json:"stats"`
  299. }
  300. func (c *config) Validate() error {
  301. if len(c.Secret.Key) == 0 || c.Secret.Host == "" {
  302. return fmt.Errorf("incorrect secret %s", c.Secret.String())
  303. }
  304. return nil
  305. }
  306. type configRaw struct {
  307. Debug bool `toml:"debug" json:"debug"`
  308. Secret string `toml:"secret" json:"secret"`
  309. BindTo string `toml:"bind-to" json:"bind-to"`
  310. TCPBuffer string `toml:"tcp-buffer" json:"tcp-buffer"`
  311. PreferIP string `toml:"prefer-ip" json:"prefer-ip"`
  312. CloakPort uint `toml:"cloak-port" json:"cloak-port"`
  313. Probes struct {
  314. Time struct {
  315. Enabled bool `toml:"enabled" json:"enabled"`
  316. AllowSkewness string `toml:"allow-skewness" json:"allow-skewness"`
  317. } `toml:"time" json:"time"`
  318. AntiReplay struct {
  319. Enabled bool `toml:"enabled" json:"enabled"`
  320. MaxSize string `toml:"max-size" json:"max-size"`
  321. ErrorRate float64 `toml:"error-rate" json:"error-rate"`
  322. } `toml:"anti-replay" json:"anti-replay"`
  323. } `toml:"probes" json:"probes"`
  324. Network struct {
  325. PublicIP struct {
  326. IPv4 string `toml:"ipv4" json:"ipv4"`
  327. IPv6 string `toml:"ipv6" json:"ipv6"`
  328. } `toml:"public-ip" json:"public-ip"`
  329. DOHIP string `toml:"doh-ip" json:"doh-ip"`
  330. Proxies []string `toml:"proxies" json:"proxies"`
  331. } `toml:"network" json:"network"`
  332. Stats struct {
  333. StatsD struct {
  334. Enabled bool `toml:"enabled" json:"enabled"`
  335. Address string `toml:"address" json:"address"`
  336. MetricPrefix string `toml:"metric-prefix" json:"metric-prefix"`
  337. } `toml:"statsd" json:"statsd"`
  338. Prometheus struct {
  339. Enabled bool `toml:"enabled" json:"enabled"`
  340. BindTo string `toml:"bind-to" json:"bind-to"`
  341. HTTPPath string `toml:"http-path" json:"http-path"`
  342. MetricPrefix string `toml:"metric-prefix" json:"metric-prefix"`
  343. } `toml:"prometheus" json:"prometheus"`
  344. } `toml:"stats" json:"stats"`
  345. }
  346. func parseConfig(reader io.Reader) (*config, error) {
  347. rawConf := &configRaw{}
  348. if err := toml.NewDecoder(reader).Decode(rawConf); err != nil {
  349. return nil, fmt.Errorf("cannot parse toml config: %w", err)
  350. }
  351. jsonBuf := &bytes.Buffer{}
  352. jsonEncoder := json.NewEncoder(jsonBuf)
  353. jsonEncoder.SetEscapeHTML(false)
  354. jsonEncoder.SetIndent("", "")
  355. if err := jsonEncoder.Encode(rawConf); err != nil {
  356. return nil, fmt.Errorf("cannot dump into interim format: %w", err)
  357. }
  358. conf := &config{}
  359. if err := json.NewDecoder(jsonBuf).Decode(conf); err != nil {
  360. return nil, fmt.Errorf("cannot parse final config: %w", err)
  361. }
  362. if err := conf.Validate(); err != nil {
  363. return nil, fmt.Errorf("cannot validate config: %w", err)
  364. }
  365. return conf, nil
  366. }