manager.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. package mtproto
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/rand"
  6. "encoding/hex"
  7. "encoding/json"
  8. "fmt"
  9. "net"
  10. "net/http"
  11. "os"
  12. "slices"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "time"
  17. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  18. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  19. )
  20. // SecretEntry is one named FakeTLS secret served by an mtg-multi process. Name is
  21. // the client email, used both as the [secrets] key and as the per-user key in the
  22. // /stats API so traffic can be attributed back to the client. AdTag is the
  23. // client's own advertising-tag override, emitted into the [secret-ad-tags]
  24. // section; empty falls back to the instance-level tag.
  25. type SecretEntry struct {
  26. Name string
  27. Secret string
  28. AdTag string
  29. }
  30. // Instance is the desired runtime configuration of one mtproto inbound. A single
  31. // mtg-multi process serves every active client's secret through the [secrets]
  32. // section, so one inbound maps to one process with many named secrets.
  33. type Instance struct {
  34. Id int
  35. Tag string
  36. Listen string
  37. Port int
  38. Secrets []SecretEntry
  39. // Optional mtg tuning; each is omitted from the generated TOML when
  40. // zero-valued so mtg falls back to its own defaults.
  41. Debug bool
  42. ProxyProtocolListener bool
  43. PreferIP string
  44. FrontingIP string
  45. FrontingPort int
  46. FrontingProxyProtocol bool
  47. // ThrottleMaxConnections caps concurrent connections across all users with a
  48. // fair-share algorithm; zero disables throttling.
  49. ThrottleMaxConnections int
  50. // AdTag is a 32-hex Telegram advertising tag; when set, mtg routes clients
  51. // through Telegram middle proxies so a sponsored channel shows in their chat
  52. // list. It is part of the reloadable secret config, so a change is applied
  53. // via /reload without dropping connections. PublicIPv4/PublicIPv6 pin the
  54. // proxy's reachable address the middle proxy needs; they are omitted when
  55. // empty so mtg auto-detects, and a change forces a restart.
  56. AdTag string
  57. PublicIPv4 string
  58. PublicIPv6 string
  59. // When RouteThroughXray is set, mtg dials Telegram through the loopback
  60. // SOCKS bridge the panel injects into the Xray config at XrayRoutePort, so
  61. // the egress obeys the core's routing rules instead of going out directly.
  62. RouteThroughXray bool
  63. XrayRoutePort int
  64. }
  65. func (inst Instance) bindTo() string {
  66. listen := inst.Listen
  67. if listen == "" {
  68. listen = "0.0.0.0"
  69. }
  70. return fmt.Sprintf("%s:%d", listen, inst.Port)
  71. }
  72. // structuralFingerprint changes whenever a value outside the [secrets] section
  73. // of the generated TOML changes. Such a change can only be applied by
  74. // restarting mtg, unlike a secrets-only change, which a reload-capable mtg can
  75. // absorb in place.
  76. func (inst Instance) structuralFingerprint() string {
  77. parts := []string{
  78. inst.bindTo(),
  79. strconv.FormatBool(inst.Debug),
  80. strconv.FormatBool(inst.ProxyProtocolListener),
  81. inst.PreferIP,
  82. inst.FrontingIP,
  83. strconv.Itoa(inst.FrontingPort),
  84. strconv.FormatBool(inst.FrontingProxyProtocol),
  85. strconv.Itoa(inst.ThrottleMaxConnections),
  86. strconv.FormatBool(inst.RouteThroughXray),
  87. strconv.Itoa(inst.XrayRoutePort),
  88. inst.PublicIPv4,
  89. inst.PublicIPv6,
  90. }
  91. return strings.Join(parts, "|")
  92. }
  93. // secretsFingerprint identifies the reloadable secret config regardless of
  94. // client order, so a reordered clients array in the stored settings does not
  95. // read as a change. It moves whenever a client is added, removed, disabled,
  96. // re-keyed, or re-tagged, or the global advertising tag changes — all of which
  97. // mtg applies in place without dropping connections.
  98. func (inst Instance) secretsFingerprint() string {
  99. pairs := make([]string, 0, len(inst.Secrets))
  100. for _, e := range inst.Secrets {
  101. pairs = append(pairs, e.Name+"="+e.Secret+";tag="+e.AdTag)
  102. }
  103. slices.Sort(pairs)
  104. return "adtag=" + inst.AdTag + "|" + strings.Join(pairs, "|")
  105. }
  106. // Traffic is a per-client traffic delta scraped from an mtg /stats endpoint. Tag
  107. // is the owning inbound's tag and Email is the client the bytes belong to.
  108. type Traffic struct {
  109. Tag string
  110. Email string
  111. Up int64
  112. Down int64
  113. }
  114. type clientCounters struct {
  115. up int64
  116. down int64
  117. }
  118. type managed struct {
  119. proc *Process
  120. tag string
  121. structuralFP string
  122. secretsFP string
  123. apiPort int
  124. apiToken string
  125. last map[string]clientCounters
  126. }
  127. // Manager owns the set of running mtg processes keyed by inbound id.
  128. type Manager struct {
  129. mu sync.Mutex
  130. procs map[int]*managed
  131. // swept records that the one-time startup cleanup of orphaned mtg
  132. // processes (survivors of a previous x-ui run) has already run.
  133. swept bool
  134. }
  135. var (
  136. managerOnce sync.Once
  137. manager *Manager
  138. )
  139. // GetManager returns the process-wide mtg manager singleton.
  140. func GetManager() *Manager {
  141. managerOnce.Do(func() {
  142. manager = &Manager{procs: map[int]*managed{}}
  143. })
  144. return manager
  145. }
  146. // InstanceFromInbound derives a desired Instance from an mtproto inbound,
  147. // building one named secret per active client. Secrets are healed on save (see
  148. // normalizeMtprotoSecret) and by the migration, so they are read as-is here to
  149. // keep the fingerprint stable across reconciles. Returns false when the inbound
  150. // is not a usable mtproto inbound or has no active client secret to serve.
  151. func InstanceFromInbound(ib *model.Inbound) (Instance, bool) {
  152. if ib == nil || ib.Protocol != model.MTProto {
  153. return Instance{}, false
  154. }
  155. settings := ib.Settings
  156. var parsed struct {
  157. ProxyProtocolListener bool `json:"proxyProtocolListener"`
  158. Debug bool `json:"debug"`
  159. DomainFronting struct {
  160. IP string `json:"ip"`
  161. Port int `json:"port"`
  162. ProxyProtocol bool `json:"proxyProtocol"`
  163. } `json:"domainFronting"`
  164. PreferIP string `json:"preferIp"`
  165. ThrottleMaxConnections int `json:"throttleMaxConnections"`
  166. RouteThroughXray bool `json:"routeThroughXray"`
  167. RouteXrayPort int `json:"routeXrayPort"`
  168. AdTag string `json:"adTag"`
  169. PublicIPv4 string `json:"publicIpv4"`
  170. PublicIPv6 string `json:"publicIpv6"`
  171. Clients []struct {
  172. Email string `json:"email"`
  173. Secret string `json:"secret"`
  174. AdTag string `json:"adTag"`
  175. Enable bool `json:"enable"`
  176. } `json:"clients"`
  177. }
  178. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  179. return Instance{}, false
  180. }
  181. secrets := make([]SecretEntry, 0, len(parsed.Clients))
  182. for _, c := range parsed.Clients {
  183. if !c.Enable || c.Secret == "" || c.Email == "" {
  184. continue
  185. }
  186. secrets = append(secrets, SecretEntry{Name: c.Email, Secret: c.Secret, AdTag: usableAdTag(c.AdTag)})
  187. }
  188. if len(secrets) == 0 {
  189. return Instance{}, false
  190. }
  191. return Instance{
  192. Id: ib.Id,
  193. Tag: ib.Tag,
  194. Listen: ib.Listen,
  195. Port: ib.Port,
  196. Secrets: secrets,
  197. Debug: parsed.Debug,
  198. ProxyProtocolListener: parsed.ProxyProtocolListener,
  199. PreferIP: parsed.PreferIP,
  200. FrontingIP: parsed.DomainFronting.IP,
  201. FrontingPort: parsed.DomainFronting.Port,
  202. FrontingProxyProtocol: parsed.DomainFronting.ProxyProtocol,
  203. ThrottleMaxConnections: parsed.ThrottleMaxConnections,
  204. RouteThroughXray: parsed.RouteThroughXray,
  205. XrayRoutePort: parsed.RouteXrayPort,
  206. AdTag: usableAdTag(parsed.AdTag),
  207. PublicIPv4: strings.TrimSpace(parsed.PublicIPv4),
  208. PublicIPv6: strings.TrimSpace(parsed.PublicIPv6),
  209. }, true
  210. }
  211. // usableAdTag returns a stored advertising tag only when it is well-formed.
  212. // The save paths validate tags, but settings can arrive from raw API payloads
  213. // or older data, and one malformed tag in a generated config makes mtg reject
  214. // the whole file — taking every client of the inbound down with it.
  215. func usableAdTag(tag string) string {
  216. tag = strings.TrimSpace(tag)
  217. if !model.ValidMtprotoAdTag(tag) {
  218. return ""
  219. }
  220. return tag
  221. }
  222. // Ensure starts the mtg process for an instance, or restarts it when its
  223. // configuration changed. A no-op when the desired process is already running.
  224. func (m *Manager) Ensure(inst Instance) error {
  225. m.mu.Lock()
  226. defer m.mu.Unlock()
  227. m.sweepOrphansLocked()
  228. return m.ensureLocked(inst)
  229. }
  230. // sweepOrphansLocked kills mtg processes left running by a previous x-ui run,
  231. // exactly once per process lifetime and before any of our own mtg are started.
  232. // Because x-ui owns every mtg process, anything alive at this point is an orphan
  233. // that would otherwise keep holding an inbound port with a stale secret.
  234. func (m *Manager) sweepOrphansLocked() {
  235. if m.swept {
  236. return
  237. }
  238. m.swept = true
  239. if n := killStrayMtgProcesses(GetBinaryPath()); n > 0 {
  240. logger.Warningf("mtproto: terminated %d orphaned mtg process(es) from a previous run", n)
  241. }
  242. }
  243. // ensureAction is what ensureLocked must do to move a running mtg process to a
  244. // desired instance: leave it alone, hot-reload only its secrets, or fully
  245. // restart it.
  246. type ensureAction int
  247. const (
  248. ensureNoop ensureAction = iota
  249. ensureReload
  250. ensureRestart
  251. )
  252. // ensureActionFor decides how to apply a desired instance to the currently
  253. // managed process. A structural change (or a dead process) forces a restart; a
  254. // secrets-only change is a candidate for an in-place reload; identical
  255. // fingerprints on a live process need nothing.
  256. func ensureActionFor(running bool, curStructFP, curSecretsFP, newStructFP, newSecretsFP string) ensureAction {
  257. if !running || curStructFP != newStructFP {
  258. return ensureRestart
  259. }
  260. if curSecretsFP != newSecretsFP {
  261. return ensureReload
  262. }
  263. return ensureNoop
  264. }
  265. func (m *Manager) ensureLocked(inst Instance) error {
  266. structFP := inst.structuralFingerprint()
  267. secFP := inst.secretsFingerprint()
  268. if cur, ok := m.procs[inst.Id]; ok {
  269. switch ensureActionFor(cur.proc.IsRunning(), cur.structuralFP, cur.secretsFP, structFP, secFP) {
  270. case ensureNoop:
  271. cur.tag = inst.Tag
  272. return nil
  273. case ensureReload:
  274. if err := writeConfig(configPathForID(inst.Id), inst, cur.apiPort, cur.apiToken); err != nil {
  275. return err
  276. }
  277. if applySecrets(cur.apiPort, cur.apiToken, inst) {
  278. cur.tag = inst.Tag
  279. cur.secretsFP = secFP
  280. logger.Infof("mtproto: applied secret update to inbound %d in place", inst.Id)
  281. return nil
  282. }
  283. logger.Warningf("mtproto: live secret update unavailable for inbound %d, restarting", inst.Id)
  284. fallthrough
  285. case ensureRestart:
  286. _ = cur.proc.Stop()
  287. delete(m.procs, inst.Id)
  288. }
  289. }
  290. apiPort, err := FreeLocalPort()
  291. if err != nil {
  292. return err
  293. }
  294. apiToken, err := newAPIToken()
  295. if err != nil {
  296. return err
  297. }
  298. cfgPath := configPathForID(inst.Id)
  299. if err := writeConfig(cfgPath, inst, apiPort, apiToken); err != nil {
  300. return err
  301. }
  302. proc := newProcess(cfgPath, fmt.Sprintf("inbound %d", inst.Id))
  303. if err := proc.Start(); err != nil {
  304. return err
  305. }
  306. m.procs[inst.Id] = &managed{
  307. proc: proc,
  308. tag: inst.Tag,
  309. structuralFP: structFP,
  310. secretsFP: secFP,
  311. apiPort: apiPort,
  312. apiToken: apiToken,
  313. last: map[string]clientCounters{},
  314. }
  315. logger.Infof("mtproto: started mtg for inbound %d on %s", inst.Id, inst.bindTo())
  316. return nil
  317. }
  318. // Remove stops and forgets the mtg process for an inbound id.
  319. func (m *Manager) Remove(id int) {
  320. m.mu.Lock()
  321. defer m.mu.Unlock()
  322. if cur, ok := m.procs[id]; ok {
  323. _ = cur.proc.Stop()
  324. delete(m.procs, id)
  325. _ = os.Remove(configPathForID(id))
  326. logger.Infof("mtproto: stopped mtg for inbound %d", id)
  327. }
  328. }
  329. // Reconcile drives the running set toward the desired instances: it stops
  330. // processes that are no longer wanted and (re)starts the rest. Used at boot
  331. // and periodically to recover from crashes.
  332. func (m *Manager) Reconcile(desired []Instance) {
  333. m.mu.Lock()
  334. defer m.mu.Unlock()
  335. m.sweepOrphansLocked()
  336. want := make(map[int]struct{}, len(desired))
  337. for _, inst := range desired {
  338. want[inst.Id] = struct{}{}
  339. }
  340. for id, cur := range m.procs {
  341. if _, ok := want[id]; !ok {
  342. _ = cur.proc.Stop()
  343. delete(m.procs, id)
  344. _ = os.Remove(configPathForID(id))
  345. }
  346. }
  347. for _, inst := range desired {
  348. if err := m.ensureLocked(inst); err != nil {
  349. logger.Warningf("mtproto: reconcile failed for inbound %d: %v", inst.Id, err)
  350. }
  351. }
  352. }
  353. // StopAll stops every managed mtg process. Called on panel shutdown.
  354. func (m *Manager) StopAll() {
  355. m.mu.Lock()
  356. defer m.mu.Unlock()
  357. for id, cur := range m.procs {
  358. _ = cur.proc.Stop()
  359. _ = os.Remove(configPathForID(id))
  360. delete(m.procs, id)
  361. }
  362. }
  363. // CollectTraffic scrapes each running mtg /stats endpoint and returns the
  364. // per-client byte deltas since the previous scrape, plus the emails of clients
  365. // with at least one live connection.
  366. func (m *Manager) CollectTraffic() ([]Traffic, []string) {
  367. type snap struct {
  368. id int
  369. apiPort int
  370. apiToken string
  371. tag string
  372. last map[string]clientCounters
  373. }
  374. m.mu.Lock()
  375. snaps := make([]snap, 0, len(m.procs))
  376. for id, cur := range m.procs {
  377. if cur.proc == nil || !cur.proc.IsRunning() {
  378. continue
  379. }
  380. lastCopy := make(map[string]clientCounters, len(cur.last))
  381. for k, v := range cur.last {
  382. lastCopy[k] = v
  383. }
  384. snaps = append(snaps, snap{id: id, apiPort: cur.apiPort, apiToken: cur.apiToken, tag: cur.tag, last: lastCopy})
  385. }
  386. m.mu.Unlock()
  387. var out []Traffic
  388. var online []string
  389. for _, s := range snaps {
  390. users, ok := scrapeStats(s.apiPort, s.apiToken)
  391. if !ok {
  392. continue
  393. }
  394. newLast := make(map[string]clientCounters, len(users))
  395. for email, u := range users {
  396. up := u.BytesIn
  397. down := u.BytesOut
  398. newLast[email] = clientCounters{up: up, down: down}
  399. if u.Connections > 0 {
  400. online = append(online, email)
  401. }
  402. prev, had := s.last[email]
  403. if !had {
  404. continue
  405. }
  406. du := up - prev.up
  407. dd := down - prev.down
  408. if du < 0 {
  409. du = 0
  410. }
  411. if dd < 0 {
  412. dd = 0
  413. }
  414. if du > 0 || dd > 0 {
  415. out = append(out, Traffic{Tag: s.tag, Email: email, Up: du, Down: dd})
  416. }
  417. }
  418. m.mu.Lock()
  419. if cur, ok := m.procs[s.id]; ok {
  420. cur.last = newLast
  421. }
  422. m.mu.Unlock()
  423. }
  424. return out, online
  425. }
  426. // FreeLocalPort asks the OS for an unused loopback TCP port. It is used both
  427. // for mtg's /stats API endpoint and to allocate the per-inbound SOCKS egress
  428. // bridge port persisted into mtproto inbound settings.
  429. func FreeLocalPort() (int, error) {
  430. l, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0")
  431. if err != nil {
  432. return 0, err
  433. }
  434. defer l.Close()
  435. return l.Addr().(*net.TCPAddr).Port, nil
  436. }
  437. // renderConfig builds the mtg-multi TOML for an instance. Top-level keys must
  438. // precede any [section] header in TOML, and [secrets] must be the final section
  439. // so trailing keys are not swallowed by another table. The layout is therefore:
  440. // top-level scalars (incl. api-bind-to and api-token), then [domain-fronting],
  441. // [network] and [throttle], then [secret-ad-tags] for clients overriding the
  442. // global advertising tag, and finally [secrets] with one named secret per
  443. // active client.
  444. func renderConfig(inst Instance, apiPort int, apiToken string) string {
  445. var b strings.Builder
  446. fmt.Fprintf(&b, "bind-to = %q\n", inst.bindTo())
  447. if inst.Debug {
  448. b.WriteString("debug = true\n")
  449. }
  450. if inst.ProxyProtocolListener {
  451. b.WriteString("proxy-protocol-listener = true\n")
  452. }
  453. if inst.PreferIP != "" {
  454. fmt.Fprintf(&b, "prefer-ip = %q\n", inst.PreferIP)
  455. }
  456. fmt.Fprintf(&b, "api-bind-to = \"127.0.0.1:%d\"\n", apiPort)
  457. if apiToken != "" {
  458. fmt.Fprintf(&b, "api-token = %q\n", apiToken)
  459. }
  460. if inst.AdTag != "" {
  461. fmt.Fprintf(&b, "ad-tag = %q\n", inst.AdTag)
  462. }
  463. if inst.PublicIPv4 != "" {
  464. fmt.Fprintf(&b, "public-ipv4 = %q\n", inst.PublicIPv4)
  465. }
  466. if inst.PublicIPv6 != "" {
  467. fmt.Fprintf(&b, "public-ipv6 = %q\n", inst.PublicIPv6)
  468. }
  469. if inst.FrontingIP != "" || inst.FrontingPort > 0 || inst.FrontingProxyProtocol {
  470. b.WriteString("\n[domain-fronting]\n")
  471. if inst.FrontingIP != "" {
  472. fmt.Fprintf(&b, "host = %q\n", inst.FrontingIP)
  473. }
  474. if inst.FrontingPort > 0 {
  475. fmt.Fprintf(&b, "port = %d\n", inst.FrontingPort)
  476. }
  477. if inst.FrontingProxyProtocol {
  478. b.WriteString("proxy-protocol = true\n")
  479. }
  480. }
  481. // When the inbound opts into Xray routing, mtg reaches Telegram through the
  482. // loopback SOCKS bridge the panel injects into the running Xray config. mtg
  483. // only supports SOCKS5 upstreams, which is exactly what the bridge exposes.
  484. if inst.RouteThroughXray && inst.XrayRoutePort > 0 {
  485. fmt.Fprintf(&b, "\n[network]\nproxies = [\"socks5://127.0.0.1:%d\"]\n", inst.XrayRoutePort)
  486. }
  487. if inst.ThrottleMaxConnections > 0 {
  488. fmt.Fprintf(&b, "\n[throttle]\nmax-connections = %d\n", inst.ThrottleMaxConnections)
  489. }
  490. // Only clients present in [secrets] may appear here: mtg rejects a config
  491. // whose [secret-ad-tags] names an unknown secret, so a disabled client's
  492. // override must vanish together with its secret.
  493. tagged := false
  494. for _, e := range inst.Secrets {
  495. if e.AdTag == "" {
  496. continue
  497. }
  498. if !tagged {
  499. b.WriteString("\n[secret-ad-tags]\n")
  500. tagged = true
  501. }
  502. fmt.Fprintf(&b, "%q = %q\n", e.Name, e.AdTag)
  503. }
  504. b.WriteString("\n[secrets]\n")
  505. for _, e := range inst.Secrets {
  506. fmt.Fprintf(&b, "%q = %q\n", e.Name, e.Secret)
  507. }
  508. return b.String()
  509. }
  510. func writeConfig(path string, inst Instance, apiPort int, apiToken string) error {
  511. if err := os.MkdirAll(configDir(), 0o750); err != nil {
  512. return err
  513. }
  514. return os.WriteFile(path, []byte(renderConfig(inst, apiPort, apiToken)), 0o640)
  515. }
  516. // statsUser is one entry of the mtg-multi /stats users map. bytes_in is traffic
  517. // the client sent to the proxy (upload) and bytes_out is what the proxy returned
  518. // (download).
  519. type statsUser struct {
  520. Connections int64 `json:"connections"`
  521. BytesIn int64 `json:"bytes_in"`
  522. BytesOut int64 `json:"bytes_out"`
  523. }
  524. type secretPutEntry struct {
  525. Secret string `json:"secret"`
  526. AdTag string `json:"ad_tag,omitempty"`
  527. }
  528. type secretsPutBody struct {
  529. Secrets map[string]secretPutEntry `json:"secrets"`
  530. AdTag string `json:"ad_tag,omitempty"`
  531. }
  532. func secretsPayload(inst Instance) secretsPutBody {
  533. secrets := make(map[string]secretPutEntry, len(inst.Secrets))
  534. for _, e := range inst.Secrets {
  535. secrets[e.Name] = secretPutEntry{Secret: e.Secret, AdTag: e.AdTag}
  536. }
  537. return secretsPutBody{Secrets: secrets, AdTag: inst.AdTag}
  538. }
  539. // newAPIToken mints the bearer token one mtg process and its manager share for
  540. // the lifetime of that process. The management API can replace the whole
  541. // secret set, so even though it only listens on loopback it must not be open
  542. // to every local process. The token lives in the generated config (mtg reads
  543. // it at startup only — a rewritten token would not apply until a restart,
  544. // which is why the reload path reuses the stored one) and in the manager's
  545. // memory, nowhere else.
  546. func newAPIToken() (string, error) {
  547. buf := make([]byte, 16)
  548. if _, err := rand.Read(buf); err != nil {
  549. return "", err
  550. }
  551. return hex.EncodeToString(buf), nil
  552. }
  553. func authorize(req *http.Request, token string) {
  554. if token != "" {
  555. req.Header.Set("Authorization", "Bearer "+token)
  556. }
  557. }
  558. // applySecrets pushes the desired secret set and advertising tags to a running
  559. // mtg-multi through its management API (PUT /secrets on the same loopback port
  560. // that serves /stats), so a client add, removal, re-key, or ad-tag change is
  561. // applied in place. mtg keeps every connection whose secret is unchanged and
  562. // closes only the removed or re-keyed ones. It returns true only on a 200: an
  563. // older binary without the endpoint (404), a refused connection, or any other
  564. // status yields false, so the caller falls back to a full restart.
  565. func applySecrets(port int, token string, inst Instance) bool {
  566. body, err := json.Marshal(secretsPayload(inst))
  567. if err != nil {
  568. return false
  569. }
  570. client := http.Client{Timeout: 3 * time.Second}
  571. req, err := http.NewRequestWithContext(context.Background(), http.MethodPut, fmt.Sprintf("http://127.0.0.1:%d/secrets", port), bytes.NewReader(body))
  572. if err != nil {
  573. return false
  574. }
  575. req.Header.Set("Content-Type", "application/json")
  576. authorize(req, token)
  577. resp, err := client.Do(req)
  578. if err != nil {
  579. return false
  580. }
  581. defer resp.Body.Close()
  582. return resp.StatusCode == http.StatusOK
  583. }
  584. // scrapeStats reads the mtg-multi /stats JSON API and returns the per-user
  585. // cumulative counters. Best-effort: an unreachable endpoint or unparseable body
  586. // yields ok=false.
  587. func scrapeStats(port int, token string) (map[string]statsUser, bool) {
  588. client := http.Client{Timeout: 3 * time.Second}
  589. req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/stats", port), nil)
  590. if err != nil {
  591. return nil, false
  592. }
  593. authorize(req, token)
  594. resp, err := client.Do(req)
  595. if err != nil {
  596. return nil, false
  597. }
  598. defer resp.Body.Close()
  599. var parsed struct {
  600. Users map[string]statsUser `json:"users"`
  601. }
  602. if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil {
  603. return nil, false
  604. }
  605. return parsed.Users, true
  606. }