remote.go 28 KB

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