remote.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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. if contentType != "" {
  214. req.Header.Set("Content-Type", contentType)
  215. }
  216. if hashHex != "" {
  217. req.Header.Set(wirecodec.HashHeader, hashHex)
  218. }
  219. if zstdEncoded {
  220. req.Header.Set("Content-Encoding", wirecodec.EncodingZstd)
  221. }
  222. client, err := r.httpClient()
  223. if err != nil {
  224. return nil, err
  225. }
  226. resp, err := client.Do(req)
  227. if err != nil {
  228. return nil, fmt.Errorf("%s %s: %w", method, path, err)
  229. }
  230. defer resp.Body.Close()
  231. r.recordCaps(resp.Header)
  232. // Validate status before reading a success payload: a non-OK response's
  233. // body is never used beyond a short diagnostic, so don't let a node force us
  234. // to buffer a large body just to return an HTTP error.
  235. if resp.StatusCode != http.StatusOK {
  236. snippet, _ := io.ReadAll(io.LimitReader(resp.Body, errBodyDiagBytes))
  237. if msg := bytes.TrimSpace(snippet); len(msg) > 0 {
  238. // %q quotes/escapes the untrusted node body so control characters or
  239. // newlines in it can't garble or inject into the error/log output.
  240. return nil, fmt.Errorf("%s %s: HTTP %d: %q", method, path, resp.StatusCode, msg)
  241. }
  242. return nil, fmt.Errorf("%s %s: HTTP %d", method, path, resp.StatusCode)
  243. }
  244. // Fast-fail on an honestly-declared oversize body; the LimitReader below is
  245. // the real guard since Content-Length is untrusted, may be absent, or is -1
  246. // under transparent decompression.
  247. if resp.ContentLength > maxRemoteResponseBytes {
  248. return nil, fmt.Errorf("%s %s: %w (content-length %d, cap %d)", method, path, errRemoteResponseTooLarge, resp.ContentLength, maxRemoteResponseBytes)
  249. }
  250. raw, err := readCappedBody(resp.Body, maxRemoteResponseBytes)
  251. if err != nil {
  252. if errors.Is(err, errRemoteResponseTooLarge) {
  253. return nil, fmt.Errorf("%s %s: %w (cap %d bytes)", method, path, err, maxRemoteResponseBytes)
  254. }
  255. return nil, fmt.Errorf("read body: %w", err)
  256. }
  257. var env envelope
  258. if err := json.Unmarshal(raw, &env); err != nil {
  259. return nil, fmt.Errorf("decode envelope: %w", err)
  260. }
  261. if !env.Success {
  262. return &env, &remoteAPIError{msg: env.Msg}
  263. }
  264. return &env, nil
  265. }
  266. func (r *Remote) resolveRemoteID(ctx context.Context, tag string) (int, error) {
  267. if id, ok := r.cacheGetTag(tag); ok {
  268. return id, nil
  269. }
  270. if err := r.refreshRemoteIDs(ctx); err != nil {
  271. return 0, err
  272. }
  273. if id, ok := r.cacheGetTag(tag); ok {
  274. return id, nil
  275. }
  276. return 0, fmt.Errorf("remote inbound with tag %q not found on node %s", tag, r.node.Name)
  277. }
  278. // nodeInboundTagPrefix is the central-panel alias for an inbound on nodeID.
  279. // Kept in sync with service.nodeTagPrefix (port_conflict.go); duplicated here
  280. // so runtime does not import service.
  281. func nodeInboundTagPrefix(nodeID int) string {
  282. return fmt.Sprintf("n%d-", nodeID)
  283. }
  284. // stripNodeInboundTagPrefix removes the central-only n<id>- prefix before
  285. // pushing an inbound to the node so Xray keeps its original tag and routing.
  286. func stripNodeInboundTagPrefix(nodeID int, tag string) string {
  287. if stripped, ok := strings.CutPrefix(tag, nodeInboundTagPrefix(nodeID)); ok {
  288. return stripped
  289. }
  290. return tag
  291. }
  292. // cacheGetTag looks up a remote inbound id by tag, tolerating an n<id>- prefix
  293. // that lives on only one of the two panels: the node may carry the bare tag
  294. // while the central panel stores the prefixed form, or vice versa.
  295. func (r *Remote) cacheGetTag(tag string) (int, bool) {
  296. if id, ok := r.cacheGet(tag); ok {
  297. return id, true
  298. }
  299. prefix := nodeInboundTagPrefix(r.node.Id)
  300. if stripped, found := strings.CutPrefix(tag, prefix); found {
  301. return r.cacheGet(stripped)
  302. }
  303. return r.cacheGet(prefix + tag)
  304. }
  305. func (r *Remote) cacheGet(tag string) (int, bool) {
  306. r.mu.RLock()
  307. defer r.mu.RUnlock()
  308. id, ok := r.remoteIDByTag[tag]
  309. return id, ok
  310. }
  311. func (r *Remote) cacheSet(tag string, id int) {
  312. r.mu.Lock()
  313. defer r.mu.Unlock()
  314. r.remoteIDByTag[tag] = id
  315. }
  316. func (r *Remote) cacheDel(tag string) {
  317. r.mu.Lock()
  318. defer r.mu.Unlock()
  319. delete(r.remoteIDByTag, tag)
  320. delete(r.pushedFP, tag)
  321. }
  322. func (r *Remote) ListRemoteTags(ctx context.Context) ([]string, error) {
  323. if err := r.refreshRemoteIDs(ctx); err != nil {
  324. return nil, err
  325. }
  326. r.mu.RLock()
  327. defer r.mu.RUnlock()
  328. tags := make([]string, 0, len(r.remoteIDByTag))
  329. for tag := range r.remoteIDByTag {
  330. tags = append(tags, tag)
  331. }
  332. return tags, nil
  333. }
  334. func (r *Remote) ListInboundOptions(ctx context.Context) ([]RemoteInboundOption, error) {
  335. env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
  336. if err != nil {
  337. return nil, err
  338. }
  339. var list []RemoteInboundOption
  340. if err := json.Unmarshal(env.Obj, &list); err != nil {
  341. return nil, fmt.Errorf("decode inbound list: %w", err)
  342. }
  343. return list, nil
  344. }
  345. func (r *Remote) refreshRemoteIDs(ctx context.Context) error {
  346. env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
  347. if err != nil {
  348. return err
  349. }
  350. var list []struct {
  351. Id int `json:"id"`
  352. Tag string `json:"tag"`
  353. }
  354. if err := json.Unmarshal(env.Obj, &list); err != nil {
  355. return fmt.Errorf("decode inbound list: %w", err)
  356. }
  357. next := make(map[string]int, len(list))
  358. for _, ib := range list {
  359. if ib.Tag == "" {
  360. continue
  361. }
  362. next[ib.Tag] = ib.Id
  363. }
  364. r.mu.Lock()
  365. // A rebuild sees only node-reported tags, so the adopted aliases must be
  366. // re-applied or a later op on an adopted inbound re-creates it as a duplicate.
  367. for centralTag, nodeTag := range r.adoptedAliases {
  368. // A tag the node reports itself is authoritative; the alias only fills
  369. // the gap left for a central tag the node knows under another name.
  370. if _, reported := next[centralTag]; reported {
  371. continue
  372. }
  373. if id, ok := next[nodeTag]; ok {
  374. next[centralTag] = id
  375. }
  376. }
  377. r.remoteIDByTag = next
  378. r.mu.Unlock()
  379. return nil
  380. }
  381. func (r *Remote) AddInbound(ctx context.Context, ib *model.Inbound) error {
  382. payload := wireInbound(ib, r.node.Id)
  383. env, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/add", payload)
  384. if err != nil {
  385. return err
  386. }
  387. var created struct {
  388. Id int `json:"id"`
  389. Tag string `json:"tag"`
  390. }
  391. if len(env.Obj) > 0 {
  392. if err := json.Unmarshal(env.Obj, &created); err == nil && created.Id > 0 && created.Tag != "" {
  393. r.cacheSet(created.Tag, created.Id)
  394. }
  395. }
  396. r.recordPushedInbound(ib)
  397. return nil
  398. }
  399. func (r *Remote) DelInbound(ctx context.Context, ib *model.Inbound) error {
  400. id, err := r.resolveRemoteID(ctx, ib.Tag)
  401. if err != nil {
  402. logger.Warning("remote DelInbound: tag", ib.Tag, "not found on", r.node.Name)
  403. return nil
  404. }
  405. if _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/del/"+strconv.Itoa(id), nil); err != nil {
  406. return err
  407. }
  408. r.cacheDel(ib.Tag)
  409. return nil
  410. }
  411. func (r *Remote) UpdateInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
  412. id, err := r.resolveRemoteID(ctx, oldIb.Tag)
  413. if err != nil {
  414. return r.AddInbound(ctx, newIb)
  415. }
  416. payload := wireInbound(newIb, r.node.Id)
  417. if _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/update/"+strconv.Itoa(id), payload); err != nil {
  418. return err
  419. }
  420. if oldIb.Tag != newIb.Tag {
  421. r.cacheDel(oldIb.Tag)
  422. }
  423. r.cacheSet(newIb.Tag, id)
  424. r.recordPushedInbound(newIb)
  425. return nil
  426. }
  427. func (r *Remote) SetInboundSubSortIndex(ctx context.Context, ib *model.Inbound, index int) error {
  428. id, err := r.resolveRemoteID(ctx, ib.Tag)
  429. if err != nil {
  430. return err
  431. }
  432. payload := url.Values{"subSortIndex": []string{strconv.Itoa(index)}}
  433. _, err = r.do(ctx, http.MethodPost, "panel/api/inbounds/"+strconv.Itoa(id)+"/subSortIndex", payload)
  434. return err
  435. }
  436. // ReconcileInbound pushes ib only when its wire payload differs from the last
  437. // successful push, or when the node no longer reports the tag (existsOnNode
  438. // false) — a node that dropped/restarted must still be re-seeded. Returns
  439. // whether a push actually happened. This turns a full-fleet reconcile from "send
  440. // every inbound's full settings" into "send only what changed".
  441. func (r *Remote) ReconcileInbound(ctx context.Context, ib *model.Inbound, existsOnNode bool) (bool, error) {
  442. fp := wireFingerprint(wireInbound(ib, r.node.Id))
  443. if existsOnNode {
  444. r.mu.RLock()
  445. prev, ok := r.pushedFP[ib.Tag]
  446. r.mu.RUnlock()
  447. if ok && prev == fp {
  448. return false, nil
  449. }
  450. }
  451. if err := r.UpdateInbound(ctx, ib, ib); err != nil {
  452. return false, err
  453. }
  454. return true, nil
  455. }
  456. // recordPushedInbound stamps the fingerprint after a full-payload push — the
  457. // only operation that proves the node holds the entire wire payload.
  458. func (r *Remote) recordPushedInbound(ib *model.Inbound) {
  459. fp := wireFingerprint(wireInbound(ib, r.node.Id))
  460. r.mu.Lock()
  461. r.pushedFP[ib.Tag] = fp
  462. r.mu.Unlock()
  463. }
  464. // RecordAdoptedInbound stamps the exact payload fingerprint after the master
  465. // adopts a node's settings serialization.
  466. func (r *Remote) RecordAdoptedInbound(ib *model.Inbound) {
  467. r.recordPushedInbound(ib)
  468. }
  469. // AdoptInboundAlias records a deployed alias without mutating either panel.
  470. // The runtime association is rediscovered after a master restart.
  471. func (r *Remote) AdoptInboundAlias(ib *model.Inbound, remote RemoteInboundOption) {
  472. r.mu.Lock()
  473. r.remoteIDByTag[remote.Tag] = remote.Id
  474. r.remoteIDByTag[ib.Tag] = remote.Id
  475. r.adoptedAliases[ib.Tag] = remote.Tag
  476. r.pushedFP[ib.Tag] = wireFingerprint(wireInbound(ib, r.node.Id))
  477. r.mu.Unlock()
  478. }
  479. func (r *Remote) AdoptedInboundAliases() []string {
  480. r.mu.RLock()
  481. defer r.mu.RUnlock()
  482. aliases := make([]string, 0, len(r.adoptedAliases))
  483. for _, alias := range r.adoptedAliases {
  484. aliases = append(aliases, alias)
  485. }
  486. return aliases
  487. }
  488. // AdvancePushedInbound moves the reconcile-skip fingerprint from an inbound's
  489. // pre-edit payload to its post-edit payload once every per-client push for the
  490. // edit succeeded. It advances only when the recorded fingerprint proves the
  491. // node held the exact pre-edit state; otherwise the stale fingerprint stays and
  492. // the next reconcile re-sends the full inbound.
  493. func (r *Remote) AdvancePushedInbound(prevIb, ib *model.Inbound) {
  494. prevFP := wireFingerprint(wireInbound(prevIb, r.node.Id))
  495. nextFP := wireFingerprint(wireInbound(ib, r.node.Id))
  496. r.mu.Lock()
  497. if r.pushedFP[ib.Tag] == prevFP {
  498. r.pushedFP[ib.Tag] = nextFP
  499. }
  500. r.mu.Unlock()
  501. }
  502. // wireFingerprint hashes a wire payload so an unchanged inbound is cheap to detect.
  503. func wireFingerprint(v url.Values) string {
  504. sum := sha256.Sum256([]byte(v.Encode()))
  505. return hex.EncodeToString(sum[:])
  506. }
  507. func (r *Remote) AddUser(ctx context.Context, ib *model.Inbound, _ map[string]any) error {
  508. return r.UpdateInbound(ctx, ib, ib)
  509. }
  510. func (r *Remote) RemoveUser(ctx context.Context, ib *model.Inbound, _ string) error {
  511. return r.UpdateInbound(ctx, ib, ib)
  512. }
  513. func (r *Remote) AddClient(ctx context.Context, ib *model.Inbound, client model.Client) error {
  514. id, err := r.resolveRemoteID(ctx, ib.Tag)
  515. if err != nil {
  516. return fmt.Errorf("remote AddClient: resolve tag %q: %w", ib.Tag, err)
  517. }
  518. payload := map[string]any{
  519. "client": client,
  520. "inboundIds": []int{id},
  521. }
  522. if _, err := r.do(ctx, http.MethodPost, "panel/api/clients/add", payload); err != nil {
  523. return err
  524. }
  525. return nil
  526. }
  527. func (r *Remote) DeleteUser(ctx context.Context, ib *model.Inbound, email string) error {
  528. if email == "" {
  529. return nil
  530. }
  531. id, err := r.resolveRemoteID(ctx, ib.Tag)
  532. if err != nil {
  533. // Can't confirm the delete reached the node — surface it so the caller
  534. // marks the node dirty and a reconcile converges, instead of silently
  535. // dropping the delete and letting the next snapshot resurrect the client.
  536. return fmt.Errorf("remote DeleteUser: resolve tag %q: %w", ib.Tag, err)
  537. }
  538. body := map[string]any{"inboundIds": []int{id}}
  539. _, err = r.do(ctx, http.MethodPost,
  540. "panel/api/clients/"+url.PathEscape(email)+"/detach", body)
  541. if err == nil {
  542. return nil
  543. }
  544. var apiErr *remoteAPIError
  545. if errors.As(err, &apiErr) && strings.Contains(strings.ToLower(apiErr.msg), "not found") {
  546. return nil
  547. }
  548. return err
  549. }
  550. func (r *Remote) DeleteClient(ctx context.Context, email string) error {
  551. if email == "" {
  552. return nil
  553. }
  554. _, err := r.do(ctx, http.MethodPost,
  555. "panel/api/clients/del/"+url.PathEscape(email), nil)
  556. if err == nil {
  557. return nil
  558. }
  559. var apiErr *remoteAPIError
  560. if errors.As(err, &apiErr) && strings.Contains(strings.ToLower(apiErr.msg), "not found") {
  561. return nil
  562. }
  563. return err
  564. }
  565. func (r *Remote) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, payload model.Client) error {
  566. if oldEmail == "" {
  567. oldEmail = payload.Email
  568. }
  569. id, err := r.resolveRemoteID(ctx, ib.Tag)
  570. if err != nil {
  571. return err
  572. }
  573. path := "panel/api/clients/update/" + url.PathEscape(oldEmail) +
  574. "?inboundIds=" + strconv.Itoa(id)
  575. if _, err := r.do(ctx, http.MethodPost, path, payload); err != nil {
  576. return err
  577. }
  578. return nil
  579. }
  580. func (r *Remote) RestartXray(ctx context.Context) error {
  581. _, err := r.do(ctx, http.MethodPost, "panel/api/server/restartXrayService", nil)
  582. return err
  583. }
  584. // UpdatePanel asks the node to run its own official self-updater (update.sh)
  585. // and restart onto the latest release. The node returns as soon as the job is
  586. // launched; the new version surfaces on the next heartbeat. When dev is true the
  587. // node is moved to the rolling dev channel instead of the latest stable release.
  588. func (r *Remote) UpdatePanel(ctx context.Context, dev bool) error {
  589. var body any
  590. if dev {
  591. body = url.Values{"dev": {"true"}}
  592. }
  593. _, err := r.do(ctx, http.MethodPost, "panel/api/server/updatePanel", body)
  594. return err
  595. }
  596. // WebCertFiles holds a node's own web TLS certificate and key file paths.
  597. type WebCertFiles struct {
  598. WebCertFile string `json:"webCertFile"`
  599. WebKeyFile string `json:"webKeyFile"`
  600. }
  601. // GetWebCertFiles fetches the node's own web TLS certificate/key file paths so
  602. // the central panel can offer them as the "Set Cert from Panel" default for a
  603. // node-assigned inbound — those paths exist on the node, the central panel's
  604. // don't. See issue #4854.
  605. func (r *Remote) GetWebCertFiles(ctx context.Context) (*WebCertFiles, error) {
  606. env, err := r.do(ctx, http.MethodGet, "panel/api/server/getWebCertFiles", nil)
  607. if err != nil {
  608. return nil, err
  609. }
  610. var files WebCertFiles
  611. if err := json.Unmarshal(env.Obj, &files); err != nil {
  612. return nil, fmt.Errorf("decode web cert files: %w", err)
  613. }
  614. return &files, nil
  615. }
  616. // GetDescendants fetches the node's read-only summaries of the nodes IT
  617. // manages, so this panel can surface them as transitive sub-nodes in a chained
  618. // topology (#4983). Best-effort: an old-build node without the endpoint returns
  619. // an error the caller ignores.
  620. func (r *Remote) GetDescendants(ctx context.Context) ([]model.NodeSummary, error) {
  621. env, err := r.do(ctx, http.MethodGet, "panel/api/server/descendants", nil)
  622. if err != nil {
  623. return nil, err
  624. }
  625. var out []model.NodeSummary
  626. if len(env.Obj) > 0 {
  627. if err := json.Unmarshal(env.Obj, &out); err != nil {
  628. return nil, fmt.Errorf("decode descendants: %w", err)
  629. }
  630. }
  631. return out, nil
  632. }
  633. func (r *Remote) ResetClientTraffic(ctx context.Context, _ *model.Inbound, email string) error {
  634. _, err := r.do(ctx, http.MethodPost,
  635. "panel/api/clients/resetTraffic/"+url.PathEscape(email), nil)
  636. return err
  637. }
  638. func (r *Remote) ResetAllTraffics(ctx context.Context) error {
  639. _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/resetAllTraffics", nil)
  640. return err
  641. }
  642. func (r *Remote) ResetInboundTraffic(ctx context.Context, ib *model.Inbound) error {
  643. _, err := r.do(ctx, http.MethodPost, fmt.Sprintf("panel/api/inbounds/%d/resetTraffic", ib.Id), nil)
  644. return err
  645. }
  646. type TrafficSnapshot struct {
  647. Inbounds []*model.Inbound
  648. OnlineEmails []string
  649. ManagedAliases []string
  650. // OnlineTree is the node's GUID-keyed online subtree (its own clients under
  651. // its panelGuid plus every descendant under theirs). Preferred over the flat
  652. // OnlineEmails so the master can attribute deeply nested clients to the real
  653. // node across a chain (#4983). Empty when the node is an old build without
  654. // the per-GUID endpoint — OnlineEmails is the fallback then.
  655. OnlineTree map[string][]string
  656. // ActiveInboundTree is the GUID-keyed subtree of inbound tags that carried
  657. // traffic within the node's online grace window. Empty when the node is an
  658. // old build without the endpoint; the master then falls back to email-only
  659. // online attribution for that node.
  660. ActiveInboundTree map[string][]string
  661. LastOnlineMap map[string]int64
  662. // HostGroups carries the node's per-inbound host overrides (TLS/SNI/
  663. // fingerprint), fetched only when the snapshot holds a not-yet-adopted tag.
  664. HostGroups []*entity.HostGroup
  665. }
  666. // FetchHostGroups pulls the node's host overrides so a freshly adopted inbound
  667. // keeps its subscription TLS/SNI/fingerprint settings on the master.
  668. func (r *Remote) FetchHostGroups(ctx context.Context) ([]*entity.HostGroup, error) {
  669. env, err := r.do(ctx, http.MethodGet, "panel/api/hosts/list", nil)
  670. if err != nil {
  671. return nil, err
  672. }
  673. var groups []*entity.HostGroup
  674. if len(env.Obj) > 0 {
  675. if err := json.Unmarshal(env.Obj, &groups); err != nil {
  676. return nil, fmt.Errorf("decode host groups: %w", err)
  677. }
  678. }
  679. return groups, nil
  680. }
  681. func (r *Remote) FetchTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, error) {
  682. snap := &TrafficSnapshot{LastOnlineMap: map[string]int64{}}
  683. envList, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
  684. if err != nil {
  685. return nil, err
  686. }
  687. if err := json.Unmarshal(envList.Obj, &snap.Inbounds); err != nil {
  688. return nil, fmt.Errorf("decode inbound list: %w", err)
  689. }
  690. // Prefer the GUID-keyed subtree; fall back to the flat list only when the
  691. // node is an old build without the per-GUID endpoint (#4983).
  692. envTree, err := r.do(ctx, http.MethodPost, "panel/api/clients/onlinesByGuid", nil)
  693. if err == nil && len(envTree.Obj) > 0 {
  694. _ = json.Unmarshal(envTree.Obj, &snap.OnlineTree)
  695. }
  696. if len(snap.OnlineTree) == 0 {
  697. envOnlines, err := r.do(ctx, http.MethodPost, "panel/api/clients/onlines", nil)
  698. if err != nil {
  699. logger.Warning("remote", r.node.Name, "onlines fetch failed:", err)
  700. } else if len(envOnlines.Obj) > 0 {
  701. _ = json.Unmarshal(envOnlines.Obj, &snap.OnlineEmails)
  702. }
  703. }
  704. envLastOnline, err := r.do(ctx, http.MethodPost, "panel/api/clients/lastOnline", nil)
  705. if err != nil {
  706. logger.Warning("remote", r.node.Name, "lastOnline fetch failed:", err)
  707. } else if len(envLastOnline.Obj) > 0 {
  708. _ = json.Unmarshal(envLastOnline.Obj, &snap.LastOnlineMap)
  709. }
  710. envActiveInbounds, err := r.do(ctx, http.MethodPost, "panel/api/clients/activeInbounds", nil)
  711. if err != nil {
  712. logger.Debugf("remote %s active inbounds fetch failed: %v", r.node.Name, err)
  713. } else if len(envActiveInbounds.Obj) > 0 {
  714. _ = json.Unmarshal(envActiveInbounds.Obj, &snap.ActiveInboundTree)
  715. }
  716. return snap, nil
  717. }
  718. // PushGlobalClientTraffics sends this panel's aggregated per-client usage to
  719. // the node, tagged with this panel's GUID so the node keeps one row per
  720. // pushing master. Display/enforcement input on the node only — the node never
  721. // folds these into the counters it reports back, so this panel's (and any
  722. // other master's) delta accounting over the node snapshot stays intact.
  723. func (r *Remote) PushGlobalClientTraffics(ctx context.Context, masterGuid string, traffics []*xray.ClientTraffic) error {
  724. payload := map[string]any{
  725. "masterGuid": masterGuid,
  726. "traffics": traffics,
  727. }
  728. _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/pushClientTraffics", payload)
  729. return err
  730. }
  731. func wireInbound(ib *model.Inbound, remoteNodeID int) url.Values {
  732. v := url.Values{}
  733. v.Set("total", strconv.FormatInt(ib.Total, 10))
  734. v.Set("remark", ib.Remark)
  735. v.Set("subSortIndex", strconv.Itoa(ib.SubSortIndex))
  736. v.Set("enable", strconv.FormatBool(ib.Enable))
  737. v.Set("expiryTime", strconv.FormatInt(ib.ExpiryTime, 10))
  738. v.Set("listen", ib.Listen)
  739. v.Set("port", strconv.Itoa(ib.Port))
  740. v.Set("protocol", string(ib.Protocol))
  741. v.Set("settings", ib.Settings)
  742. v.Set("streamSettings", sanitizeStreamSettingsForRemote(ib.StreamSettings))
  743. tag := ib.Tag
  744. if remoteNodeID > 0 {
  745. tag = stripNodeInboundTagPrefix(remoteNodeID, tag)
  746. }
  747. v.Set("tag", tag)
  748. v.Set("sniffing", ib.Sniffing)
  749. shareAddrStrategy := strings.TrimSpace(ib.ShareAddrStrategy)
  750. switch shareAddrStrategy {
  751. case "listen", "custom":
  752. default:
  753. shareAddrStrategy = "node"
  754. }
  755. v.Set("shareAddrStrategy", shareAddrStrategy)
  756. v.Set("shareAddr", ib.ShareAddr)
  757. v.Set("disableFlow", strconv.FormatBool(ib.DisableFlow))
  758. if ib.TrafficReset != "" {
  759. v.Set("trafficReset", ib.TrafficReset)
  760. }
  761. if ib.TrafficResetDay > 0 {
  762. v.Set("trafficResetDay", strconv.Itoa(ib.TrafficResetDay))
  763. }
  764. return v
  765. }
  766. // sanitizeStreamSettingsForRemote strips file-based TLS certificate paths
  767. // from the StreamSettings before sending to a remote node, but ONLY when
  768. // inline certificate content (certificate / key) is also present in the same
  769. // entry. In that case the file paths are redundant and stripping them avoids
  770. // confusion when the central panel's local paths don't exist on the remote.
  771. //
  772. // When a certificate entry contains ONLY file paths (no inline content) the
  773. // paths are left untouched: the user explicitly entered paths that exist on
  774. // the remote node's filesystem, and removing them would leave Xray with TLS
  775. // configured but no certificate, causing Xray to crash on the remote node.
  776. func sanitizeStreamSettingsForRemote(streamSettings string) string {
  777. if streamSettings == "" {
  778. return streamSettings
  779. }
  780. var stream map[string]any
  781. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  782. return streamSettings
  783. }
  784. tlsSettings, ok := stream["tlsSettings"].(map[string]any)
  785. if !ok {
  786. return streamSettings
  787. }
  788. certificates, ok := tlsSettings["certificates"].([]any)
  789. if !ok {
  790. return streamSettings
  791. }
  792. changed := false
  793. for _, cert := range certificates {
  794. c, ok := cert.(map[string]any)
  795. if !ok {
  796. continue
  797. }
  798. // Only strip file paths when inline content is present so that the
  799. // remote Xray still has a valid certificate to use.
  800. hasCertFile := c["certificateFile"] != nil && c["certificateFile"] != ""
  801. hasKeyFile := c["keyFile"] != nil && c["keyFile"] != ""
  802. hasCertInline := isNonEmptySlice(c["certificate"])
  803. hasKeyInline := isNonEmptySlice(c["key"])
  804. if hasCertFile && hasCertInline {
  805. delete(c, "certificateFile")
  806. changed = true
  807. }
  808. if hasKeyFile && hasKeyInline {
  809. delete(c, "keyFile")
  810. changed = true
  811. }
  812. }
  813. if !changed {
  814. return streamSettings
  815. }
  816. out, err := json.Marshal(stream)
  817. if err != nil {
  818. return streamSettings
  819. }
  820. return string(out)
  821. }
  822. // isNonEmptySlice reports whether v is a non-nil, non-empty JSON array value.
  823. func isNonEmptySlice(v any) bool {
  824. s, ok := v.([]any)
  825. return ok && len(s) > 0
  826. }
  827. func (r *Remote) FetchAllClientIps(ctx context.Context) ([]model.InboundClientIps, error) {
  828. env, err := r.do(ctx, http.MethodGet, "panel/api/server/clientIps", nil)
  829. if err != nil {
  830. return nil, err
  831. }
  832. var ips []model.InboundClientIps
  833. if len(env.Obj) > 0 {
  834. if err := json.Unmarshal(env.Obj, &ips); err != nil {
  835. return nil, fmt.Errorf("decode client ips: %w", err)
  836. }
  837. }
  838. return ips, nil
  839. }
  840. func (r *Remote) PushAllClientIps(ctx context.Context, ips []model.InboundClientIps) error {
  841. _, err := r.do(ctx, http.MethodPost, "panel/api/server/clientIps", ips)
  842. return err
  843. }
  844. // FetchClientIpsByGuid pulls the node's per-node IP attribution subtree
  845. // (guid -> email -> observed IPs). Unlike FetchAllClientIps (the flat union the
  846. // master also pushes back), this preserves which physical node each IP is on.
  847. // Returns an empty map for older nodes that lack the endpoint.
  848. func (r *Remote) FetchClientIpsByGuid(ctx context.Context) (map[string]map[string][]model.ClientIpEntry, error) {
  849. env, err := r.do(ctx, http.MethodPost, "panel/api/clients/clientIpsByGuid", nil)
  850. if err != nil {
  851. return nil, err
  852. }
  853. out := map[string]map[string][]model.ClientIpEntry{}
  854. if len(env.Obj) > 0 {
  855. if err := json.Unmarshal(env.Obj, &out); err != nil {
  856. return nil, fmt.Errorf("decode client ips by guid: %w", err)
  857. }
  858. }
  859. return out, nil
  860. }