manager.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. package mtproto
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. "os"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  14. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  15. )
  16. // Instance is the desired runtime configuration of one mtproto inbound.
  17. type Instance struct {
  18. Id int
  19. Tag string
  20. Listen string
  21. Port int
  22. Secret string
  23. // Optional mtg tuning; each is omitted from the generated TOML when
  24. // zero-valued so mtg falls back to its own defaults.
  25. Debug bool
  26. ProxyProtocolListener bool
  27. PreferIP string
  28. FrontingIP string
  29. FrontingPort int
  30. FrontingProxyProtocol bool
  31. // When RouteThroughXray is set, mtg dials Telegram through the loopback
  32. // SOCKS bridge the panel injects into the Xray config at XrayRoutePort, so
  33. // the egress obeys the core's routing rules instead of going out directly.
  34. RouteThroughXray bool
  35. XrayRoutePort int
  36. }
  37. func (inst Instance) bindTo() string {
  38. listen := inst.Listen
  39. if listen == "" {
  40. listen = "0.0.0.0"
  41. }
  42. return fmt.Sprintf("%s:%d", listen, inst.Port)
  43. }
  44. // fingerprint changes whenever any value that ends up in the generated TOML
  45. // changes, so ensureLocked restarts mtg when the operator edits a setting.
  46. func (inst Instance) fingerprint() string {
  47. return strings.Join([]string{
  48. inst.bindTo(),
  49. inst.Secret,
  50. strconv.FormatBool(inst.Debug),
  51. strconv.FormatBool(inst.ProxyProtocolListener),
  52. inst.PreferIP,
  53. inst.FrontingIP,
  54. strconv.Itoa(inst.FrontingPort),
  55. strconv.FormatBool(inst.FrontingProxyProtocol),
  56. strconv.FormatBool(inst.RouteThroughXray),
  57. strconv.Itoa(inst.XrayRoutePort),
  58. }, "|")
  59. }
  60. // Traffic is a per-inbound traffic delta scraped from an mtg metrics endpoint.
  61. type Traffic struct {
  62. Tag string
  63. Up int64
  64. Down int64
  65. }
  66. type managed struct {
  67. proc *Process
  68. tag string
  69. fingerprint string
  70. metricsPort int
  71. lastUp int64
  72. lastDown int64
  73. haveLast bool
  74. }
  75. // Manager owns the set of running mtg processes keyed by inbound id.
  76. type Manager struct {
  77. mu sync.Mutex
  78. procs map[int]*managed
  79. // swept records that the one-time startup cleanup of orphaned mtg
  80. // processes (survivors of a previous x-ui run) has already run.
  81. swept bool
  82. }
  83. var (
  84. managerOnce sync.Once
  85. manager *Manager
  86. )
  87. // GetManager returns the process-wide mtg manager singleton.
  88. func GetManager() *Manager {
  89. managerOnce.Do(func() {
  90. manager = &Manager{procs: map[int]*managed{}}
  91. })
  92. return manager
  93. }
  94. // InstanceFromInbound derives a desired Instance from an mtproto inbound,
  95. // healing the FakeTLS secret so it always matches the configured domain.
  96. // Returns false when the inbound is not a usable mtproto inbound.
  97. func InstanceFromInbound(ib *model.Inbound) (Instance, bool) {
  98. if ib == nil || ib.Protocol != model.MTProto {
  99. return Instance{}, false
  100. }
  101. settings := ib.Settings
  102. if healed, ok := model.HealMtprotoSecret(settings); ok {
  103. settings = healed
  104. }
  105. var parsed struct {
  106. Secret string `json:"secret"`
  107. Debug bool `json:"debug"`
  108. ProxyProtocolListener bool `json:"proxyProtocolListener"`
  109. PreferIP string `json:"preferIp"`
  110. DomainFronting struct {
  111. IP string `json:"ip"`
  112. Port int `json:"port"`
  113. ProxyProtocol bool `json:"proxyProtocol"`
  114. } `json:"domainFronting"`
  115. RouteThroughXray bool `json:"routeThroughXray"`
  116. RouteXrayPort int `json:"routeXrayPort"`
  117. }
  118. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  119. return Instance{}, false
  120. }
  121. if parsed.Secret == "" {
  122. return Instance{}, false
  123. }
  124. return Instance{
  125. Id: ib.Id,
  126. Tag: ib.Tag,
  127. Listen: ib.Listen,
  128. Port: ib.Port,
  129. Secret: parsed.Secret,
  130. Debug: parsed.Debug,
  131. ProxyProtocolListener: parsed.ProxyProtocolListener,
  132. PreferIP: parsed.PreferIP,
  133. FrontingIP: parsed.DomainFronting.IP,
  134. FrontingPort: parsed.DomainFronting.Port,
  135. FrontingProxyProtocol: parsed.DomainFronting.ProxyProtocol,
  136. RouteThroughXray: parsed.RouteThroughXray,
  137. XrayRoutePort: parsed.RouteXrayPort,
  138. }, true
  139. }
  140. // Ensure starts the mtg process for an instance, or restarts it when its
  141. // configuration changed. A no-op when the desired process is already running.
  142. func (m *Manager) Ensure(inst Instance) error {
  143. m.mu.Lock()
  144. defer m.mu.Unlock()
  145. m.sweepOrphansLocked()
  146. return m.ensureLocked(inst)
  147. }
  148. // sweepOrphansLocked kills mtg processes left running by a previous x-ui run,
  149. // exactly once per process lifetime and before any of our own mtg are started.
  150. // Because x-ui owns every mtg process, anything alive at this point is an orphan
  151. // that would otherwise keep holding an inbound port with a stale secret.
  152. func (m *Manager) sweepOrphansLocked() {
  153. if m.swept {
  154. return
  155. }
  156. m.swept = true
  157. if n := killStrayMtgProcesses(GetBinaryPath()); n > 0 {
  158. logger.Warningf("mtproto: terminated %d orphaned mtg process(es) from a previous run", n)
  159. }
  160. }
  161. func (m *Manager) ensureLocked(inst Instance) error {
  162. fp := inst.fingerprint()
  163. if cur, ok := m.procs[inst.Id]; ok {
  164. if cur.fingerprint == fp && cur.proc.IsRunning() {
  165. cur.tag = inst.Tag
  166. return nil
  167. }
  168. cur.proc.Stop()
  169. delete(m.procs, inst.Id)
  170. }
  171. metricsPort, err := FreeLocalPort()
  172. if err != nil {
  173. return err
  174. }
  175. cfgPath := configPathForID(inst.Id)
  176. if err := writeConfig(cfgPath, inst, metricsPort); err != nil {
  177. return err
  178. }
  179. proc := newProcess(cfgPath, fmt.Sprintf("inbound %d", inst.Id))
  180. if err := proc.Start(); err != nil {
  181. return err
  182. }
  183. m.procs[inst.Id] = &managed{
  184. proc: proc,
  185. tag: inst.Tag,
  186. fingerprint: fp,
  187. metricsPort: metricsPort,
  188. }
  189. logger.Infof("mtproto: started mtg for inbound %d on %s", inst.Id, inst.bindTo())
  190. return nil
  191. }
  192. // Remove stops and forgets the mtg process for an inbound id.
  193. func (m *Manager) Remove(id int) {
  194. m.mu.Lock()
  195. defer m.mu.Unlock()
  196. if cur, ok := m.procs[id]; ok {
  197. cur.proc.Stop()
  198. delete(m.procs, id)
  199. _ = os.Remove(configPathForID(id))
  200. logger.Infof("mtproto: stopped mtg for inbound %d", id)
  201. }
  202. }
  203. // Reconcile drives the running set toward the desired instances: it stops
  204. // processes that are no longer wanted and (re)starts the rest. Used at boot
  205. // and periodically to recover from crashes.
  206. func (m *Manager) Reconcile(desired []Instance) {
  207. m.mu.Lock()
  208. defer m.mu.Unlock()
  209. m.sweepOrphansLocked()
  210. want := make(map[int]struct{}, len(desired))
  211. for _, inst := range desired {
  212. want[inst.Id] = struct{}{}
  213. }
  214. for id, cur := range m.procs {
  215. if _, ok := want[id]; !ok {
  216. cur.proc.Stop()
  217. delete(m.procs, id)
  218. _ = os.Remove(configPathForID(id))
  219. }
  220. }
  221. for _, inst := range desired {
  222. if err := m.ensureLocked(inst); err != nil {
  223. logger.Warningf("mtproto: reconcile failed for inbound %d: %v", inst.Id, err)
  224. }
  225. }
  226. }
  227. // StopAll stops every managed mtg process. Called on panel shutdown.
  228. func (m *Manager) StopAll() {
  229. m.mu.Lock()
  230. defer m.mu.Unlock()
  231. for id, cur := range m.procs {
  232. _ = cur.proc.Stop()
  233. _ = os.Remove(configPathForID(id))
  234. delete(m.procs, id)
  235. }
  236. }
  237. // CollectTraffic scrapes each running mtg metrics endpoint and returns the
  238. // per-inbound byte deltas since the previous scrape.
  239. func (m *Manager) CollectTraffic() []Traffic {
  240. // Snapshot the state we need under the lock, then release before doing
  241. // network I/O so that Ensure/Reconcile/Remove are not blocked.
  242. type snap struct {
  243. id int
  244. metricsPort int
  245. tag string
  246. haveLast bool
  247. lastUp int64
  248. lastDown int64
  249. }
  250. m.mu.Lock()
  251. snaps := make([]snap, 0, len(m.procs))
  252. for id, cur := range m.procs {
  253. if cur.proc == nil || !cur.proc.IsRunning() {
  254. continue
  255. }
  256. snaps = append(snaps, snap{
  257. id: id,
  258. metricsPort: cur.metricsPort,
  259. tag: cur.tag,
  260. haveLast: cur.haveLast,
  261. lastUp: cur.lastUp,
  262. lastDown: cur.lastDown,
  263. })
  264. }
  265. m.mu.Unlock()
  266. out := make([]Traffic, 0, len(snaps))
  267. for _, s := range snaps {
  268. up, down, ok := scrapeTraffic(s.metricsPort)
  269. if !ok {
  270. continue
  271. }
  272. var du, dd int64
  273. if s.haveLast {
  274. du = up - s.lastUp
  275. dd = down - s.lastDown
  276. if du < 0 {
  277. du = 0
  278. }
  279. if dd < 0 {
  280. dd = 0
  281. }
  282. }
  283. // Re-acquire lock to persist the new baseline, but only if the entry
  284. // still exists (it may have been removed during the scrape).
  285. m.mu.Lock()
  286. if cur, ok := m.procs[s.id]; ok {
  287. cur.lastUp = up
  288. cur.lastDown = down
  289. cur.haveLast = true
  290. }
  291. m.mu.Unlock()
  292. if s.haveLast && (du > 0 || dd > 0) {
  293. out = append(out, Traffic{Tag: s.tag, Up: du, Down: dd})
  294. }
  295. }
  296. return out
  297. }
  298. // FreeLocalPort asks the OS for an unused loopback TCP port. It is used both
  299. // for mtg's metrics endpoint and to allocate the per-inbound SOCKS egress
  300. // bridge port persisted into mtproto inbound settings.
  301. func FreeLocalPort() (int, error) {
  302. l, err := net.Listen("tcp", "127.0.0.1:0")
  303. if err != nil {
  304. return 0, err
  305. }
  306. defer l.Close()
  307. return l.Addr().(*net.TCPAddr).Port, nil
  308. }
  309. // renderConfig builds the mtg TOML for an instance. Top-level keys must precede
  310. // any [section] header in TOML, so the layout is: required keys, then the
  311. // optional scalar tuning, then [domain-fronting], and finally [stats.prometheus]
  312. // — which x-ui always emits and scrapes for traffic (see scrapeTraffic).
  313. func renderConfig(inst Instance, metricsPort int) string {
  314. var b strings.Builder
  315. fmt.Fprintf(&b, "secret = %q\n", inst.Secret)
  316. fmt.Fprintf(&b, "bind-to = %q\n", inst.bindTo())
  317. if inst.Debug {
  318. b.WriteString("debug = true\n")
  319. }
  320. if inst.ProxyProtocolListener {
  321. b.WriteString("proxy-protocol-listener = true\n")
  322. }
  323. if inst.PreferIP != "" {
  324. fmt.Fprintf(&b, "prefer-ip = %q\n", inst.PreferIP)
  325. }
  326. if inst.FrontingIP != "" || inst.FrontingPort > 0 || inst.FrontingProxyProtocol {
  327. b.WriteString("\n[domain-fronting]\n")
  328. if inst.FrontingIP != "" {
  329. fmt.Fprintf(&b, "ip = %q\n", inst.FrontingIP)
  330. }
  331. if inst.FrontingPort > 0 {
  332. fmt.Fprintf(&b, "port = %d\n", inst.FrontingPort)
  333. }
  334. if inst.FrontingProxyProtocol {
  335. b.WriteString("proxy-protocol = true\n")
  336. }
  337. }
  338. // When the inbound opts into Xray routing, mtg reaches Telegram through the
  339. // loopback SOCKS bridge the panel injects into the running Xray config. mtg
  340. // only supports SOCKS5 upstreams, which is exactly what the bridge exposes.
  341. if inst.RouteThroughXray && inst.XrayRoutePort > 0 {
  342. fmt.Fprintf(&b, "\n[network]\nproxies = [\"socks5://127.0.0.1:%d\"]\n", inst.XrayRoutePort)
  343. }
  344. fmt.Fprintf(&b, "\n[stats.prometheus]\nenabled = true\nbind-to = \"127.0.0.1:%d\"\nhttp-path = \"/metrics\"\nmetric-prefix = \"mtg\"\n", metricsPort)
  345. return b.String()
  346. }
  347. func writeConfig(path string, inst Instance, metricsPort int) error {
  348. if err := os.MkdirAll(configDir(), 0o750); err != nil {
  349. return err
  350. }
  351. return os.WriteFile(path, []byte(renderConfig(inst, metricsPort)), 0o640)
  352. }
  353. // scrapeTraffic reads the mtg Prometheus metrics endpoint and sums byte
  354. // counters by direction. mtg exposes a traffic counter labelled with a
  355. // direction; "to_telegram" is treated as upload and "to_client" as download.
  356. // Best-effort: an unreachable endpoint or unrecognised format yields ok=false.
  357. func scrapeTraffic(port int) (up int64, down int64, ok bool) {
  358. client := http.Client{Timeout: 3 * time.Second}
  359. resp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d/metrics", port))
  360. if err != nil {
  361. return 0, 0, false
  362. }
  363. defer resp.Body.Close()
  364. scanner := bufio.NewScanner(resp.Body)
  365. scanner.Buffer(make([]byte, 64*1024), 1024*1024)
  366. found := false
  367. for scanner.Scan() {
  368. line := strings.TrimSpace(scanner.Text())
  369. if line == "" || line[0] == '#' || !strings.Contains(line, "traffic") {
  370. continue
  371. }
  372. name, labels, value, perr := parseMetricLine(line)
  373. if perr != nil || !strings.HasPrefix(name, "mtg") {
  374. continue
  375. }
  376. switch labels["direction"] {
  377. case "to_telegram", "egress", "up":
  378. up += int64(value)
  379. case "to_client", "ingress", "down":
  380. down += int64(value)
  381. default:
  382. down += int64(value)
  383. }
  384. found = true
  385. }
  386. if err := scanner.Err(); err != nil {
  387. logger.Debug("mtproto: metrics scan error:", err)
  388. }
  389. return up, down, found
  390. }
  391. func parseMetricLine(line string) (name string, labels map[string]string, value float64, err error) {
  392. labels = map[string]string{}
  393. rest := line
  394. if brace := strings.IndexByte(line, '{'); brace >= 0 {
  395. name = line[:brace]
  396. end := strings.IndexByte(line, '}')
  397. if end < brace {
  398. return "", nil, 0, fmt.Errorf("malformed metric line")
  399. }
  400. for _, kv := range strings.Split(line[brace+1:end], ",") {
  401. eq := strings.IndexByte(kv, '=')
  402. if eq < 0 {
  403. continue
  404. }
  405. labels[strings.TrimSpace(kv[:eq])] = strings.Trim(strings.TrimSpace(kv[eq+1:]), `"`)
  406. }
  407. rest = strings.TrimSpace(line[end+1:])
  408. } else {
  409. fields := strings.Fields(line)
  410. if len(fields) < 2 {
  411. return "", nil, 0, fmt.Errorf("malformed metric line")
  412. }
  413. name = fields[0]
  414. rest = fields[1]
  415. }
  416. valFields := strings.Fields(rest)
  417. if len(valFields) == 0 {
  418. return "", nil, 0, fmt.Errorf("missing metric value")
  419. }
  420. value, err = strconv.ParseFloat(valFields[0], 64)
  421. if err != nil {
  422. return "", nil, 0, err
  423. }
  424. return name, labels, value, nil
  425. }