1
0

remote.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  1. package runtime
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "net"
  12. "net/http"
  13. "net/url"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "time"
  18. "github.com/mhsanaei/3x-ui/v3/internal/crypto/nodetoken"
  19. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  20. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  21. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  22. "github.com/mhsanaei/3x-ui/v3/internal/util/wirecodec"
  23. "github.com/mhsanaei/3x-ui/v3/internal/web/entity"
  24. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  25. )
  26. const remoteHTTPTimeout = 10 * time.Second
  27. // zstdMinBodyBytes is the smallest body worth compressing; below it the framing
  28. // overhead can outweigh the savings.
  29. const zstdMinBodyBytes = 1024
  30. // maxRemoteResponseBytes caps a single node RPC's response body. It bounds the
  31. // wire/decompressed size of one response — the real guard against a broken or
  32. // hostile node streaming an unbounded body. It is NOT a process-wide memory
  33. // bound: concurrent RPCs and the decoded JSON can each exceed it, so
  34. // endpoint-specific caps and a concurrency budget remain follow-ups. Node
  35. // responses (traffic snapshots, client-IP lists, inbound options) are JSON and
  36. // stay well under it.
  37. const maxRemoteResponseBytes = 64 << 20 // 64 MiB
  38. // errBodyDiagBytes bounds how much of a non-OK error body we read for a
  39. // diagnostic snippet (and to let small-error connections be reused) without
  40. // buffering a potentially huge or hostile error payload.
  41. const errBodyDiagBytes = 8 << 10 // 8 KiB
  42. // errRemoteResponseTooLarge is returned when a node response exceeds the cap.
  43. var errRemoteResponseTooLarge = errors.New("remote response exceeds size limit")
  44. // readCappedBody reads all of r but rejects bodies larger than limit, returning
  45. // errRemoteResponseTooLarge. It reads at most limit+1 bytes so a body of exactly
  46. // limit is accepted and the first oversize byte is detected without buffering
  47. // more.
  48. func readCappedBody(r io.Reader, limit int64) ([]byte, error) {
  49. raw, err := io.ReadAll(io.LimitReader(r, limit+1))
  50. if err != nil {
  51. return nil, err
  52. }
  53. if int64(len(raw)) > limit {
  54. return nil, errRemoteResponseTooLarge
  55. }
  56. return raw, nil
  57. }
  58. type envelope struct {
  59. Success bool `json:"success"`
  60. Msg string `json:"msg"`
  61. Obj json.RawMessage `json:"obj"`
  62. }
  63. // remoteAPIError is a node-panel envelope failure (HTTP 200, success=false),
  64. // distinct from transport/HTTP-status errors so callers can trust its message.
  65. type remoteAPIError struct{ msg string }
  66. func (e *remoteAPIError) Error() string { return "remote: " + e.msg }
  67. type Remote struct {
  68. node *model.Node
  69. mu sync.RWMutex
  70. remoteIDByTag map[string]int
  71. adoptedAliases map[string]string
  72. // pushedFP holds the fingerprint of the last inbound wire payload successfully
  73. // pushed, keyed by panel-side tag, so reconcile can skip re-sending an
  74. // unchanged inbound. Guarded by mu; dropped with the Remote on node config change.
  75. pushedFP map[string]string
  76. // supportsZstd is learned from the node's X-3x-Node-Caps response header; once
  77. // seen, config pushes to this node are zstd-compressed. Old nodes never set
  78. // it, so they keep receiving plain bodies (mixed-version safe).
  79. supportsZstd bool
  80. // Per-node client honoring the TLS verify mode, built once and reused; a
  81. // node config change drops the cached Remote so the next one rebuilds it.
  82. clientOnce sync.Once
  83. client *http.Client
  84. clientErr error
  85. egressResolver NodeEgressResolver
  86. }
  87. type RemoteInboundOption struct {
  88. Id int `json:"id"`
  89. Tag string `json:"tag"`
  90. Remark string `json:"remark"`
  91. Listen string `json:"listen"`
  92. Protocol model.Protocol `json:"protocol"`
  93. Port int `json:"port"`
  94. }
  95. func NewRemote(n *model.Node, r NodeEgressResolver) *Remote {
  96. return &Remote{
  97. node: n,
  98. remoteIDByTag: make(map[string]int),
  99. adoptedAliases: make(map[string]string),
  100. pushedFP: make(map[string]string),
  101. egressResolver: r,
  102. }
  103. }
  104. func (r *Remote) Name() string { return "node:" + r.node.Name }
  105. func (r *Remote) nodeSupportsZstd() bool {
  106. r.mu.RLock()
  107. defer r.mu.RUnlock()
  108. return r.supportsZstd
  109. }
  110. // recordCaps learns the node's capabilities from a response header so later
  111. // pushes can use the negotiated envelope.
  112. func (r *Remote) recordCaps(h http.Header) {
  113. if !strings.Contains(h.Get(wirecodec.CapsHeader), wirecodec.CapZstd) {
  114. return
  115. }
  116. r.mu.Lock()
  117. r.supportsZstd = true
  118. r.mu.Unlock()
  119. }
  120. // httpClient lazily builds and caches the per-node client honoring the TLS
  121. // verify mode, so Remote ops don't fall back to system CA on skip/pin (#5264).
  122. func (r *Remote) httpClient() (*http.Client, error) {
  123. r.clientOnce.Do(func() {
  124. proxyURL := ""
  125. if r.node.OutboundTag != "" && r.egressResolver != nil {
  126. proxyURL = r.egressResolver.NodeEgressProxyURL(r.node.Id)
  127. }
  128. r.client, r.clientErr = HTTPClientForNode(r.node, proxyURL)
  129. })
  130. return r.client, r.clientErr
  131. }
  132. func (r *Remote) baseURL() (string, error) {
  133. addr, err := netsafe.NormalizeHost(r.node.Address)
  134. if err != nil {
  135. return "", err
  136. }
  137. scheme := r.node.Scheme
  138. if scheme != "http" && scheme != "https" {
  139. scheme = "https"
  140. }
  141. if r.node.Port <= 0 || r.node.Port > 65535 {
  142. return "", fmt.Errorf("invalid node port %d", r.node.Port)
  143. }
  144. bp := r.node.BasePath
  145. if !strings.HasSuffix(bp, "/") {
  146. bp += "/"
  147. }
  148. u := &url.URL{
  149. Scheme: scheme,
  150. Host: net.JoinHostPort(addr, strconv.Itoa(r.node.Port)),
  151. Path: bp,
  152. }
  153. return u.String(), nil
  154. }
  155. func (r *Remote) do(ctx context.Context, method, path string, body any) (*envelope, error) {
  156. // mtls nodes authenticate via the client certificate, so a bearer token is
  157. // optional for them; every other mode still requires one.
  158. if r.node.ApiToken == "" && r.node.TlsVerifyMode != "mtls" {
  159. return nil, errors.New("node has no API token configured")
  160. }
  161. base, err := r.baseURL()
  162. if err != nil {
  163. return nil, err
  164. }
  165. target := base + strings.TrimPrefix(path, "/")
  166. var (
  167. bodyBytes []byte
  168. contentType string
  169. )
  170. switch b := body.(type) {
  171. case nil:
  172. case url.Values:
  173. bodyBytes = []byte(b.Encode())
  174. contentType = "application/x-www-form-urlencoded"
  175. default:
  176. buf, jerr := json.Marshal(b)
  177. if jerr != nil {
  178. return nil, fmt.Errorf("marshal body: %w", jerr)
  179. }
  180. bodyBytes = buf
  181. contentType = "application/json"
  182. }
  183. // Attach the integrity hash of the uncompressed body unconditionally (a new
  184. // node verifies it, an old one ignores it), and zstd-compress only when the
  185. // node advertised support and the body is worth it.
  186. var (
  187. reqBody io.Reader
  188. hashHex string
  189. zstdEncoded bool
  190. )
  191. if bodyBytes != nil {
  192. hashHex = wirecodec.Sha256Hex(bodyBytes)
  193. if len(bodyBytes) >= zstdMinBodyBytes && r.nodeSupportsZstd() {
  194. bodyBytes = wirecodec.Compress(bodyBytes)
  195. zstdEncoded = true
  196. }
  197. reqBody = bytes.NewReader(bodyBytes)
  198. }
  199. cctx, cancel := context.WithTimeout(netsafe.ContextWithAllowPrivate(ctx, r.node.AllowPrivateAddress), remoteHTTPTimeout)
  200. defer cancel()
  201. req, err := http.NewRequestWithContext(cctx, method, target, reqBody)
  202. if err != nil {
  203. return nil, err
  204. }
  205. if r.node.ApiToken != "" {
  206. token, err := nodetoken.Decrypt(r.node.Id, r.node.ApiToken)
  207. if err != nil {
  208. return nil, fmt.Errorf("decrypt node token: %w", err)
  209. }
  210. req.Header.Set("Authorization", "Bearer "+token)
  211. }
  212. req.Header.Set("Accept", "application/json")
  213. req.Header.Set(wirecodec.MasterPushHeader, "1")
  214. if contentType != "" {
  215. req.Header.Set("Content-Type", contentType)
  216. }
  217. if hashHex != "" {
  218. req.Header.Set(wirecodec.HashHeader, hashHex)
  219. }
  220. if zstdEncoded {
  221. req.Header.Set("Content-Encoding", wirecodec.EncodingZstd)
  222. }
  223. client, err := r.httpClient()
  224. if err != nil {
  225. return nil, err
  226. }
  227. resp, err := client.Do(req)
  228. if err != nil {
  229. return nil, fmt.Errorf("%s %s: %w", method, path, err)
  230. }
  231. defer resp.Body.Close()
  232. r.recordCaps(resp.Header)
  233. // Validate status before reading a success payload: a non-OK response's
  234. // body is never used beyond a short diagnostic, so don't let a node force us
  235. // to buffer a large body just to return an HTTP error.
  236. if resp.StatusCode != http.StatusOK {
  237. snippet, _ := io.ReadAll(io.LimitReader(resp.Body, errBodyDiagBytes))
  238. if msg := bytes.TrimSpace(snippet); len(msg) > 0 {
  239. // %q quotes/escapes the untrusted node body so control characters or
  240. // newlines in it can't garble or inject into the error/log output.
  241. return nil, fmt.Errorf("%s %s: HTTP %d: %q", method, path, resp.StatusCode, msg)
  242. }
  243. return nil, fmt.Errorf("%s %s: HTTP %d", method, path, resp.StatusCode)
  244. }
  245. // Fast-fail on an honestly-declared oversize body; the LimitReader below is
  246. // the real guard since Content-Length is untrusted, may be absent, or is -1
  247. // under transparent decompression.
  248. if resp.ContentLength > maxRemoteResponseBytes {
  249. return nil, fmt.Errorf("%s %s: %w (content-length %d, cap %d)", method, path, errRemoteResponseTooLarge, resp.ContentLength, maxRemoteResponseBytes)
  250. }
  251. raw, err := readCappedBody(resp.Body, maxRemoteResponseBytes)
  252. if err != nil {
  253. if errors.Is(err, errRemoteResponseTooLarge) {
  254. return nil, fmt.Errorf("%s %s: %w (cap %d bytes)", method, path, err, maxRemoteResponseBytes)
  255. }
  256. return nil, fmt.Errorf("read body: %w", err)
  257. }
  258. var env envelope
  259. if err := json.Unmarshal(raw, &env); err != nil {
  260. return nil, fmt.Errorf("decode envelope: %w", err)
  261. }
  262. if !env.Success {
  263. return &env, &remoteAPIError{msg: env.Msg}
  264. }
  265. return &env, nil
  266. }
  267. func (r *Remote) resolveRemoteID(ctx context.Context, tag string) (int, error) {
  268. if id, ok := r.cacheGetTag(tag); ok {
  269. return id, nil
  270. }
  271. if err := r.refreshRemoteIDs(ctx); err != nil {
  272. return 0, err
  273. }
  274. if id, ok := r.cacheGetTag(tag); ok {
  275. return id, nil
  276. }
  277. return 0, fmt.Errorf("remote inbound with tag %q not found on node %s", tag, r.node.Name)
  278. }
  279. // nodeInboundTagPrefix is the central-panel alias for an inbound on nodeID.
  280. // Kept in sync with service.nodeTagPrefix (port_conflict.go); duplicated here
  281. // so runtime does not import service.
  282. func nodeInboundTagPrefix(nodeID int) string {
  283. return fmt.Sprintf("n%d-", nodeID)
  284. }
  285. // stripNodeInboundTagPrefix removes the central-only n<id>- prefix before
  286. // pushing an inbound to the node so Xray keeps its original tag and routing.
  287. func stripNodeInboundTagPrefix(nodeID int, tag string) string {
  288. if stripped, ok := strings.CutPrefix(tag, nodeInboundTagPrefix(nodeID)); ok {
  289. return stripped
  290. }
  291. return tag
  292. }
  293. // cacheGetTag looks up a remote inbound id by tag, tolerating an n<id>- prefix
  294. // that lives on only one of the two panels: the node may carry the bare tag
  295. // while the central panel stores the prefixed form, or vice versa.
  296. func (r *Remote) cacheGetTag(tag string) (int, bool) {
  297. if id, ok := r.cacheGet(tag); ok {
  298. return id, true
  299. }
  300. prefix := nodeInboundTagPrefix(r.node.Id)
  301. if stripped, found := strings.CutPrefix(tag, prefix); found {
  302. return r.cacheGet(stripped)
  303. }
  304. return r.cacheGet(prefix + tag)
  305. }
  306. func (r *Remote) cacheGet(tag string) (int, bool) {
  307. r.mu.RLock()
  308. defer r.mu.RUnlock()
  309. id, ok := r.remoteIDByTag[tag]
  310. return id, ok
  311. }
  312. func (r *Remote) cacheSet(tag string, id int) {
  313. r.mu.Lock()
  314. defer r.mu.Unlock()
  315. r.remoteIDByTag[tag] = id
  316. }
  317. func (r *Remote) cacheDel(tag string) {
  318. r.mu.Lock()
  319. defer r.mu.Unlock()
  320. delete(r.remoteIDByTag, tag)
  321. delete(r.pushedFP, tag)
  322. }
  323. // forgetTag drops every tag form cacheGetTag would match, once the node reports
  324. // none of them, so the next resolve re-reads the node instead of a deleted id.
  325. func (r *Remote) forgetTag(tag string) {
  326. prefix := nodeInboundTagPrefix(r.node.Id)
  327. bare := strings.TrimPrefix(tag, prefix)
  328. r.cacheDel(bare)
  329. r.cacheDel(prefix + bare)
  330. }
  331. func (r *Remote) ListRemoteTags(ctx context.Context) ([]string, error) {
  332. if err := r.refreshRemoteIDs(ctx); err != nil {
  333. return nil, err
  334. }
  335. r.mu.RLock()
  336. defer r.mu.RUnlock()
  337. tags := make([]string, 0, len(r.remoteIDByTag))
  338. for tag := range r.remoteIDByTag {
  339. tags = append(tags, tag)
  340. }
  341. return tags, nil
  342. }
  343. func (r *Remote) ListInboundOptions(ctx context.Context) ([]RemoteInboundOption, error) {
  344. env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
  345. if err != nil {
  346. return nil, err
  347. }
  348. var list []RemoteInboundOption
  349. if err := json.Unmarshal(env.Obj, &list); err != nil {
  350. return nil, fmt.Errorf("decode inbound list: %w", err)
  351. }
  352. return list, nil
  353. }
  354. func (r *Remote) refreshRemoteIDs(ctx context.Context) error {
  355. env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
  356. if err != nil {
  357. return err
  358. }
  359. var list []struct {
  360. Id int `json:"id"`
  361. Tag string `json:"tag"`
  362. }
  363. if err := json.Unmarshal(env.Obj, &list); err != nil {
  364. return fmt.Errorf("decode inbound list: %w", err)
  365. }
  366. next := make(map[string]int, len(list))
  367. for _, ib := range list {
  368. if ib.Tag == "" {
  369. continue
  370. }
  371. next[ib.Tag] = ib.Id
  372. }
  373. r.mu.Lock()
  374. // A rebuild sees only node-reported tags, so the adopted aliases must be
  375. // re-applied or a later op on an adopted inbound re-creates it as a duplicate.
  376. for centralTag, nodeTag := range r.adoptedAliases {
  377. // A tag the node reports itself is authoritative; the alias only fills
  378. // the gap left for a central tag the node knows under another name.
  379. if _, reported := next[centralTag]; reported {
  380. continue
  381. }
  382. if id, ok := next[nodeTag]; ok {
  383. next[centralTag] = id
  384. }
  385. }
  386. r.remoteIDByTag = next
  387. r.mu.Unlock()
  388. return nil
  389. }
  390. func (r *Remote) AddInbound(ctx context.Context, ib *model.Inbound) error {
  391. payload := wireInbound(ib, r.node.Id)
  392. env, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/add", payload)
  393. if err != nil {
  394. return err
  395. }
  396. var created struct {
  397. Id int `json:"id"`
  398. Tag string `json:"tag"`
  399. }
  400. if len(env.Obj) > 0 {
  401. if err := json.Unmarshal(env.Obj, &created); err == nil && created.Id > 0 && created.Tag != "" {
  402. r.cacheSet(created.Tag, created.Id)
  403. }
  404. }
  405. r.recordPushedInbound(ib)
  406. return nil
  407. }
  408. func (r *Remote) DelInbound(ctx context.Context, ib *model.Inbound) error {
  409. id, err := r.resolveRemoteID(ctx, ib.Tag)
  410. if err != nil {
  411. logger.Warning("remote DelInbound: tag", ib.Tag, "not found on", r.node.Name)
  412. return nil
  413. }
  414. if _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/del/"+strconv.Itoa(id), nil); err != nil {
  415. return err
  416. }
  417. r.cacheDel(ib.Tag)
  418. return nil
  419. }
  420. func (r *Remote) UpdateInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
  421. id, err := r.resolveRemoteID(ctx, oldIb.Tag)
  422. if err != nil {
  423. return r.AddInbound(ctx, newIb)
  424. }
  425. payload := wireInbound(newIb, r.node.Id)
  426. if _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/update/"+strconv.Itoa(id), payload); err != nil {
  427. return err
  428. }
  429. if oldIb.Tag != newIb.Tag {
  430. r.cacheDel(oldIb.Tag)
  431. }
  432. r.cacheSet(newIb.Tag, id)
  433. r.recordPushedInbound(newIb)
  434. return nil
  435. }
  436. func (r *Remote) SetInboundSubSortIndex(ctx context.Context, ib *model.Inbound, index int) error {
  437. id, err := r.resolveRemoteID(ctx, ib.Tag)
  438. if err != nil {
  439. return err
  440. }
  441. payload := url.Values{"subSortIndex": []string{strconv.Itoa(index)}}
  442. _, err = r.do(ctx, http.MethodPost, "panel/api/inbounds/"+strconv.Itoa(id)+"/subSortIndex", payload)
  443. return err
  444. }
  445. // ReconcileInbound pushes ib only when its wire payload differs from the last
  446. // successful push, or when the node no longer reports the tag (existsOnNode
  447. // false) — a node that dropped/restarted must still be re-seeded. Returns
  448. // whether a push actually happened. This turns a full-fleet reconcile from "send
  449. // every inbound's full settings" into "send only what changed".
  450. func (r *Remote) ReconcileInbound(ctx context.Context, ib *model.Inbound, existsOnNode bool) (bool, error) {
  451. fp := wireFingerprint(wireInbound(ib, r.node.Id))
  452. if existsOnNode {
  453. r.mu.RLock()
  454. prev, ok := r.pushedFP[ib.Tag]
  455. r.mu.RUnlock()
  456. if ok && prev == fp {
  457. return false, nil
  458. }
  459. } else {
  460. r.forgetTag(ib.Tag)
  461. }
  462. if err := r.UpdateInbound(ctx, ib, ib); err != nil {
  463. return false, err
  464. }
  465. return true, nil
  466. }
  467. // recordPushedInbound stamps the fingerprint after a full-payload push — the
  468. // only operation that proves the node holds the entire wire payload.
  469. func (r *Remote) recordPushedInbound(ib *model.Inbound) {
  470. fp := wireFingerprint(wireInbound(ib, r.node.Id))
  471. r.mu.Lock()
  472. r.pushedFP[ib.Tag] = fp
  473. r.mu.Unlock()
  474. }
  475. // RecordAdoptedInbound stamps the exact payload fingerprint after the master
  476. // adopts a node's settings serialization.
  477. func (r *Remote) RecordAdoptedInbound(ib *model.Inbound) {
  478. r.recordPushedInbound(ib)
  479. }
  480. // AdoptInboundAlias records a deployed alias without mutating either panel.
  481. // The runtime association is rediscovered after a master restart.
  482. func (r *Remote) AdoptInboundAlias(ib *model.Inbound, remote RemoteInboundOption) {
  483. r.mu.Lock()
  484. r.remoteIDByTag[remote.Tag] = remote.Id
  485. r.remoteIDByTag[ib.Tag] = remote.Id
  486. r.adoptedAliases[ib.Tag] = remote.Tag
  487. r.pushedFP[ib.Tag] = wireFingerprint(wireInbound(ib, r.node.Id))
  488. r.mu.Unlock()
  489. }
  490. func (r *Remote) AdoptedInboundAliases() []string {
  491. r.mu.RLock()
  492. defer r.mu.RUnlock()
  493. aliases := make([]string, 0, len(r.adoptedAliases))
  494. for _, alias := range r.adoptedAliases {
  495. aliases = append(aliases, alias)
  496. }
  497. return aliases
  498. }
  499. // AdvancePushedInbound moves the reconcile-skip fingerprint from an inbound's
  500. // pre-edit payload to its post-edit payload once every per-client push for the
  501. // edit succeeded. It advances only when the recorded fingerprint proves the
  502. // node held the exact pre-edit state; otherwise the stale fingerprint stays and
  503. // the next reconcile re-sends the full inbound.
  504. func (r *Remote) AdvancePushedInbound(prevIb, ib *model.Inbound) {
  505. prevFP := wireFingerprint(wireInbound(prevIb, r.node.Id))
  506. nextFP := wireFingerprint(wireInbound(ib, r.node.Id))
  507. r.mu.Lock()
  508. if r.pushedFP[ib.Tag] == prevFP {
  509. r.pushedFP[ib.Tag] = nextFP
  510. }
  511. r.mu.Unlock()
  512. }
  513. // wireFingerprint hashes a wire payload so an unchanged inbound is cheap to detect.
  514. func wireFingerprint(v url.Values) string {
  515. sum := sha256.Sum256([]byte(v.Encode()))
  516. return hex.EncodeToString(sum[:])
  517. }
  518. func (r *Remote) AddUser(ctx context.Context, ib *model.Inbound, _ map[string]any) error {
  519. return r.UpdateInbound(ctx, ib, ib)
  520. }
  521. func (r *Remote) RemoveUser(ctx context.Context, ib *model.Inbound, _ string) error {
  522. return r.UpdateInbound(ctx, ib, ib)
  523. }
  524. func (r *Remote) AddClient(ctx context.Context, ib *model.Inbound, client model.Client) error {
  525. id, err := r.resolveRemoteID(ctx, ib.Tag)
  526. if err != nil {
  527. return fmt.Errorf("remote AddClient: resolve tag %q: %w", ib.Tag, err)
  528. }
  529. payload := map[string]any{
  530. "client": client,
  531. "inboundIds": []int{id},
  532. }
  533. if _, err := r.do(ctx, http.MethodPost, "panel/api/clients/add", payload); err != nil {
  534. return err
  535. }
  536. return nil
  537. }
  538. func (r *Remote) DeleteUser(ctx context.Context, ib *model.Inbound, email string) error {
  539. if email == "" {
  540. return nil
  541. }
  542. id, err := r.resolveRemoteID(ctx, ib.Tag)
  543. if err != nil {
  544. // Can't confirm the delete reached the node — surface it so the caller
  545. // marks the node dirty and a reconcile converges, instead of silently
  546. // dropping the delete and letting the next snapshot resurrect the client.
  547. return fmt.Errorf("remote DeleteUser: resolve tag %q: %w", ib.Tag, err)
  548. }
  549. body := map[string]any{"inboundIds": []int{id}}
  550. _, err = r.do(ctx, http.MethodPost,
  551. "panel/api/clients/"+url.PathEscape(email)+"/detach", body)
  552. if err == nil {
  553. return nil
  554. }
  555. var apiErr *remoteAPIError
  556. if errors.As(err, &apiErr) && strings.Contains(strings.ToLower(apiErr.msg), "not found") {
  557. return nil
  558. }
  559. return err
  560. }
  561. func (r *Remote) DeleteClient(ctx context.Context, email string) error {
  562. if email == "" {
  563. return nil
  564. }
  565. _, err := r.do(ctx, http.MethodPost,
  566. "panel/api/clients/del/"+url.PathEscape(email), nil)
  567. if err == nil {
  568. return nil
  569. }
  570. var apiErr *remoteAPIError
  571. if errors.As(err, &apiErr) && strings.Contains(strings.ToLower(apiErr.msg), "not found") {
  572. return nil
  573. }
  574. return err
  575. }
  576. func (r *Remote) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, payload model.Client) error {
  577. if oldEmail == "" {
  578. oldEmail = payload.Email
  579. }
  580. id, err := r.resolveRemoteID(ctx, ib.Tag)
  581. if err != nil {
  582. return err
  583. }
  584. path := "panel/api/clients/update/" + url.PathEscape(oldEmail) +
  585. "?inboundIds=" + strconv.Itoa(id)
  586. if _, err := r.do(ctx, http.MethodPost, path, payload); err != nil {
  587. return err
  588. }
  589. return nil
  590. }
  591. func (r *Remote) RestartXray(ctx context.Context) error {
  592. _, err := r.do(ctx, http.MethodPost, "panel/api/server/restartXrayService", nil)
  593. return err
  594. }
  595. // UpdatePanel asks the node to run its own official self-updater (update.sh)
  596. // and restart onto the latest release. The node returns as soon as the job is
  597. // launched; the new version surfaces on the next heartbeat. When dev is true the
  598. // node is moved to the rolling dev channel instead of the latest stable release.
  599. func (r *Remote) UpdatePanel(ctx context.Context, dev bool) error {
  600. var body any
  601. if dev {
  602. body = url.Values{"dev": {"true"}}
  603. }
  604. _, err := r.do(ctx, http.MethodPost, "panel/api/server/updatePanel", body)
  605. return err
  606. }
  607. // WebCertFiles holds a node's own web TLS certificate and key file paths.
  608. type WebCertFiles struct {
  609. WebCertFile string `json:"webCertFile"`
  610. WebKeyFile string `json:"webKeyFile"`
  611. }
  612. // GetWebCertFiles fetches the node's own web TLS certificate/key file paths so
  613. // the central panel can offer them as the "Set Cert from Panel" default for a
  614. // node-assigned inbound — those paths exist on the node, the central panel's
  615. // don't. See issue #4854.
  616. func (r *Remote) GetWebCertFiles(ctx context.Context) (*WebCertFiles, error) {
  617. env, err := r.do(ctx, http.MethodGet, "panel/api/server/getWebCertFiles", nil)
  618. if err != nil {
  619. return nil, err
  620. }
  621. var files WebCertFiles
  622. if err := json.Unmarshal(env.Obj, &files); err != nil {
  623. return nil, fmt.Errorf("decode web cert files: %w", err)
  624. }
  625. return &files, nil
  626. }
  627. // GetDescendants fetches the node's read-only summaries of the nodes IT
  628. // manages, so this panel can surface them as transitive sub-nodes in a chained
  629. // topology (#4983). Best-effort: an old-build node without the endpoint returns
  630. // an error the caller ignores.
  631. func (r *Remote) GetDescendants(ctx context.Context) ([]model.NodeSummary, error) {
  632. env, err := r.do(ctx, http.MethodGet, "panel/api/server/descendants", nil)
  633. if err != nil {
  634. return nil, err
  635. }
  636. var out []model.NodeSummary
  637. if len(env.Obj) > 0 {
  638. if err := json.Unmarshal(env.Obj, &out); err != nil {
  639. return nil, fmt.Errorf("decode descendants: %w", err)
  640. }
  641. }
  642. return out, nil
  643. }
  644. func (r *Remote) ResetClientTraffic(ctx context.Context, _ *model.Inbound, email string) error {
  645. _, err := r.do(ctx, http.MethodPost,
  646. "panel/api/clients/resetTraffic/"+url.PathEscape(email), nil)
  647. return err
  648. }
  649. // ResetClientTraffics zeroes many clients on the node in one request.
  650. func (r *Remote) ResetClientTraffics(ctx context.Context, emails []string) error {
  651. _, err := r.do(ctx, http.MethodPost, "panel/api/clients/bulkResetTraffic", map[string]any{"emails": emails})
  652. return err
  653. }
  654. func (r *Remote) ResetAllTraffics(ctx context.Context) error {
  655. _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/resetAllTraffics", nil)
  656. return err
  657. }
  658. func (r *Remote) ResetInboundTraffic(ctx context.Context, ib *model.Inbound) error {
  659. id, err := r.resolveRemoteID(ctx, ib.Tag)
  660. if err != nil {
  661. return fmt.Errorf("remote ResetInboundTraffic: resolve tag %q: %w", ib.Tag, err)
  662. }
  663. _, err = r.do(ctx, http.MethodPost, fmt.Sprintf("panel/api/inbounds/%d/resetTraffic", id), nil)
  664. return err
  665. }
  666. type TrafficSnapshot struct {
  667. Inbounds []*model.Inbound
  668. OnlineEmails []string
  669. ManagedAliases []string
  670. // OnlineTree is the node's GUID-keyed online subtree (its own clients under
  671. // its panelGuid plus every descendant under theirs). Preferred over the flat
  672. // OnlineEmails so the master can attribute deeply nested clients to the real
  673. // node across a chain (#4983). Empty when the node is an old build without
  674. // the per-GUID endpoint — OnlineEmails is the fallback then.
  675. OnlineTree map[string][]string
  676. // ActiveInboundTree is the GUID-keyed subtree of inbound tags that carried
  677. // traffic within the node's online grace window. Empty when the node is an
  678. // old build without the endpoint; the master then falls back to email-only
  679. // online attribution for that node.
  680. ActiveInboundTree map[string][]string
  681. LastOnlineMap map[string]int64
  682. // HostGroups carries the node's per-inbound host overrides (TLS/SNI/
  683. // fingerprint), fetched only when the snapshot holds a not-yet-adopted tag.
  684. HostGroups []*entity.HostGroup
  685. }
  686. // FetchHostGroups pulls the node's host overrides so a freshly adopted inbound
  687. // keeps its subscription TLS/SNI/fingerprint settings on the master.
  688. func (r *Remote) FetchHostGroups(ctx context.Context) ([]*entity.HostGroup, error) {
  689. env, err := r.do(ctx, http.MethodGet, "panel/api/hosts/list", nil)
  690. if err != nil {
  691. return nil, err
  692. }
  693. var groups []*entity.HostGroup
  694. if len(env.Obj) > 0 {
  695. if err := json.Unmarshal(env.Obj, &groups); err != nil {
  696. return nil, fmt.Errorf("decode host groups: %w", err)
  697. }
  698. }
  699. return groups, nil
  700. }
  701. func (r *Remote) FetchTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, error) {
  702. snap := &TrafficSnapshot{LastOnlineMap: map[string]int64{}}
  703. envList, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
  704. if err != nil {
  705. return nil, err
  706. }
  707. if err := json.Unmarshal(envList.Obj, &snap.Inbounds); err != nil {
  708. return nil, fmt.Errorf("decode inbound list: %w", err)
  709. }
  710. // Prefer the GUID-keyed subtree; fall back to the flat list only when the
  711. // node is an old build without the per-GUID endpoint (#4983).
  712. envTree, err := r.do(ctx, http.MethodPost, "panel/api/clients/onlinesByGuid", nil)
  713. if err == nil && len(envTree.Obj) > 0 {
  714. _ = json.Unmarshal(envTree.Obj, &snap.OnlineTree)
  715. }
  716. if len(snap.OnlineTree) == 0 {
  717. envOnlines, err := r.do(ctx, http.MethodPost, "panel/api/clients/onlines", nil)
  718. if err != nil {
  719. logger.Warning("remote", r.node.Name, "onlines fetch failed:", err)
  720. } else if len(envOnlines.Obj) > 0 {
  721. _ = json.Unmarshal(envOnlines.Obj, &snap.OnlineEmails)
  722. }
  723. }
  724. envLastOnline, err := r.do(ctx, http.MethodPost, "panel/api/clients/lastOnline", nil)
  725. if err != nil {
  726. logger.Warning("remote", r.node.Name, "lastOnline fetch failed:", err)
  727. } else if len(envLastOnline.Obj) > 0 {
  728. _ = json.Unmarshal(envLastOnline.Obj, &snap.LastOnlineMap)
  729. }
  730. envActiveInbounds, err := r.do(ctx, http.MethodPost, "panel/api/clients/activeInbounds", nil)
  731. if err != nil {
  732. logger.Debugf("remote %s active inbounds fetch failed: %v", r.node.Name, err)
  733. } else if len(envActiveInbounds.Obj) > 0 {
  734. _ = json.Unmarshal(envActiveInbounds.Obj, &snap.ActiveInboundTree)
  735. }
  736. return snap, nil
  737. }
  738. // PushGlobalClientTraffics sends this panel's aggregated per-client usage to
  739. // the node, tagged with this panel's GUID so the node keeps one row per
  740. // pushing master. Display/enforcement input on the node only — the node never
  741. // folds these into the counters it reports back, so this panel's (and any
  742. // other master's) delta accounting over the node snapshot stays intact.
  743. func (r *Remote) PushGlobalClientTraffics(ctx context.Context, masterGuid string, traffics []*xray.ClientTraffic) error {
  744. payload := map[string]any{
  745. "masterGuid": masterGuid,
  746. "traffics": traffics,
  747. }
  748. _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/pushClientTraffics", payload)
  749. return err
  750. }
  751. func wireInbound(ib *model.Inbound, remoteNodeID int) url.Values {
  752. v := url.Values{}
  753. v.Set("total", strconv.FormatInt(ib.Total, 10))
  754. v.Set("remark", ib.Remark)
  755. v.Set("subSortIndex", strconv.Itoa(ib.SubSortIndex))
  756. v.Set("excludeFromSub", strconv.FormatBool(ib.ExcludeFromSub))
  757. v.Set("enable", strconv.FormatBool(ib.Enable))
  758. v.Set("expiryTime", strconv.FormatInt(ib.ExpiryTime, 10))
  759. v.Set("listen", ib.Listen)
  760. v.Set("port", strconv.Itoa(ib.Port))
  761. v.Set("protocol", string(ib.Protocol))
  762. v.Set("settings", ib.Settings)
  763. v.Set("streamSettings", sanitizeStreamSettingsForRemote(ib.StreamSettings))
  764. tag := ib.Tag
  765. if remoteNodeID > 0 {
  766. tag = stripNodeInboundTagPrefix(remoteNodeID, tag)
  767. }
  768. v.Set("tag", tag)
  769. v.Set("sniffing", ib.Sniffing)
  770. shareAddrStrategy := strings.TrimSpace(ib.ShareAddrStrategy)
  771. switch shareAddrStrategy {
  772. case "listen", "custom":
  773. default:
  774. shareAddrStrategy = "node"
  775. }
  776. v.Set("shareAddrStrategy", shareAddrStrategy)
  777. v.Set("shareAddr", ib.ShareAddr)
  778. v.Set("disableFlow", strconv.FormatBool(ib.DisableFlow))
  779. if ib.TrafficReset != "" {
  780. v.Set("trafficReset", ib.TrafficReset)
  781. }
  782. if ib.TrafficResetDay > 0 {
  783. v.Set("trafficResetDay", strconv.Itoa(ib.TrafficResetDay))
  784. }
  785. return v
  786. }
  787. // sanitizeStreamSettingsForRemote strips file-based TLS certificate paths
  788. // from the StreamSettings before sending to a remote node, but ONLY when
  789. // inline certificate content (certificate / key) is also present in the same
  790. // entry. In that case the file paths are redundant and stripping them avoids
  791. // confusion when the central panel's local paths don't exist on the remote.
  792. //
  793. // When a certificate entry contains ONLY file paths (no inline content) the
  794. // paths are left untouched: the user explicitly entered paths that exist on
  795. // the remote node's filesystem, and removing them would leave Xray with TLS
  796. // configured but no certificate, causing Xray to crash on the remote node.
  797. func sanitizeStreamSettingsForRemote(streamSettings string) string {
  798. if streamSettings == "" {
  799. return streamSettings
  800. }
  801. var stream map[string]any
  802. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  803. return streamSettings
  804. }
  805. tlsSettings, ok := stream["tlsSettings"].(map[string]any)
  806. if !ok {
  807. return streamSettings
  808. }
  809. certificates, ok := tlsSettings["certificates"].([]any)
  810. if !ok {
  811. return streamSettings
  812. }
  813. changed := false
  814. for _, cert := range certificates {
  815. c, ok := cert.(map[string]any)
  816. if !ok {
  817. continue
  818. }
  819. // Only strip file paths when inline content is present so that the
  820. // remote Xray still has a valid certificate to use.
  821. hasCertFile := c["certificateFile"] != nil && c["certificateFile"] != ""
  822. hasKeyFile := c["keyFile"] != nil && c["keyFile"] != ""
  823. hasCertInline := isNonEmptySlice(c["certificate"])
  824. hasKeyInline := isNonEmptySlice(c["key"])
  825. if hasCertFile && hasCertInline {
  826. delete(c, "certificateFile")
  827. changed = true
  828. }
  829. if hasKeyFile && hasKeyInline {
  830. delete(c, "keyFile")
  831. changed = true
  832. }
  833. }
  834. if !changed {
  835. return streamSettings
  836. }
  837. out, err := json.Marshal(stream)
  838. if err != nil {
  839. return streamSettings
  840. }
  841. return string(out)
  842. }
  843. // isNonEmptySlice reports whether v is a non-nil, non-empty JSON array value.
  844. func isNonEmptySlice(v any) bool {
  845. s, ok := v.([]any)
  846. return ok && len(s) > 0
  847. }
  848. func (r *Remote) FetchAllClientIps(ctx context.Context) ([]model.InboundClientIps, error) {
  849. env, err := r.do(ctx, http.MethodGet, "panel/api/server/clientIps", nil)
  850. if err != nil {
  851. return nil, err
  852. }
  853. var ips []model.InboundClientIps
  854. if len(env.Obj) > 0 {
  855. if err := json.Unmarshal(env.Obj, &ips); err != nil {
  856. return nil, fmt.Errorf("decode client ips: %w", err)
  857. }
  858. }
  859. return ips, nil
  860. }
  861. func (r *Remote) PushAllClientIps(ctx context.Context, ips []model.InboundClientIps) error {
  862. _, err := r.do(ctx, http.MethodPost, "panel/api/server/clientIps", ips)
  863. return err
  864. }
  865. // FetchClientIpsByGuid pulls the node's per-node IP attribution subtree
  866. // (guid -> email -> observed IPs). Unlike FetchAllClientIps (the flat union the
  867. // master also pushes back), this preserves which physical node each IP is on.
  868. // Returns an empty map for older nodes that lack the endpoint.
  869. func (r *Remote) FetchClientIpsByGuid(ctx context.Context) (map[string]map[string][]model.ClientIpEntry, error) {
  870. env, err := r.do(ctx, http.MethodPost, "panel/api/clients/clientIpsByGuid", nil)
  871. if err != nil {
  872. return nil, err
  873. }
  874. out := map[string]map[string][]model.ClientIpEntry{}
  875. if len(env.Obj) > 0 {
  876. if err := json.Unmarshal(env.Obj, &out); err != nil {
  877. return nil, fmt.Errorf("decode client ips by guid: %w", err)
  878. }
  879. }
  880. return out, nil
  881. }