1
0

remote.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. package runtime
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net"
  10. "net/http"
  11. "net/url"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  17. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  18. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  19. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  20. )
  21. const remoteHTTPTimeout = 10 * time.Second
  22. var remoteHTTPClient = &http.Client{
  23. Transport: &http.Transport{
  24. MaxIdleConns: 64,
  25. MaxIdleConnsPerHost: 4,
  26. IdleConnTimeout: 60 * time.Second,
  27. DialContext: netsafe.SSRFGuardedDialContext,
  28. },
  29. }
  30. type envelope struct {
  31. Success bool `json:"success"`
  32. Msg string `json:"msg"`
  33. Obj json.RawMessage `json:"obj"`
  34. }
  35. type Remote struct {
  36. node *model.Node
  37. mu sync.RWMutex
  38. remoteIDByTag map[string]int
  39. }
  40. func NewRemote(n *model.Node) *Remote {
  41. return &Remote{
  42. node: n,
  43. remoteIDByTag: make(map[string]int),
  44. }
  45. }
  46. func (r *Remote) Name() string { return "node:" + r.node.Name }
  47. func (r *Remote) baseURL() (string, error) {
  48. addr, err := netsafe.NormalizeHost(r.node.Address)
  49. if err != nil {
  50. return "", err
  51. }
  52. scheme := r.node.Scheme
  53. if scheme != "http" && scheme != "https" {
  54. scheme = "https"
  55. }
  56. if r.node.Port <= 0 || r.node.Port > 65535 {
  57. return "", fmt.Errorf("invalid node port %d", r.node.Port)
  58. }
  59. bp := r.node.BasePath
  60. if bp == "" {
  61. bp = "/"
  62. }
  63. if !strings.HasSuffix(bp, "/") {
  64. bp += "/"
  65. }
  66. u := &url.URL{
  67. Scheme: scheme,
  68. Host: net.JoinHostPort(addr, strconv.Itoa(r.node.Port)),
  69. Path: bp,
  70. }
  71. return u.String(), nil
  72. }
  73. func (r *Remote) do(ctx context.Context, method, path string, body any) (*envelope, error) {
  74. if r.node.ApiToken == "" {
  75. return nil, errors.New("node has no API token configured")
  76. }
  77. base, err := r.baseURL()
  78. if err != nil {
  79. return nil, err
  80. }
  81. target := base + strings.TrimPrefix(path, "/")
  82. var (
  83. reqBody io.Reader
  84. contentType string
  85. )
  86. switch b := body.(type) {
  87. case nil:
  88. case url.Values:
  89. reqBody = strings.NewReader(b.Encode())
  90. contentType = "application/x-www-form-urlencoded"
  91. default:
  92. buf, jerr := json.Marshal(b)
  93. if jerr != nil {
  94. return nil, fmt.Errorf("marshal body: %w", jerr)
  95. }
  96. reqBody = bytes.NewReader(buf)
  97. contentType = "application/json"
  98. }
  99. cctx, cancel := context.WithTimeout(netsafe.ContextWithAllowPrivate(ctx, r.node.AllowPrivateAddress), remoteHTTPTimeout)
  100. defer cancel()
  101. req, err := http.NewRequestWithContext(cctx, method, target, reqBody)
  102. if err != nil {
  103. return nil, err
  104. }
  105. req.Header.Set("Authorization", "Bearer "+r.node.ApiToken)
  106. req.Header.Set("Accept", "application/json")
  107. if contentType != "" {
  108. req.Header.Set("Content-Type", contentType)
  109. }
  110. resp, err := remoteHTTPClient.Do(req)
  111. if err != nil {
  112. return nil, fmt.Errorf("%s %s: %w", method, path, err)
  113. }
  114. defer resp.Body.Close()
  115. raw, err := io.ReadAll(resp.Body)
  116. if err != nil {
  117. return nil, fmt.Errorf("read body: %w", err)
  118. }
  119. if resp.StatusCode != http.StatusOK {
  120. return nil, fmt.Errorf("%s %s: HTTP %d", method, path, resp.StatusCode)
  121. }
  122. var env envelope
  123. if err := json.Unmarshal(raw, &env); err != nil {
  124. return nil, fmt.Errorf("decode envelope: %w", err)
  125. }
  126. if !env.Success {
  127. return &env, fmt.Errorf("remote: %s", env.Msg)
  128. }
  129. return &env, nil
  130. }
  131. func (r *Remote) resolveRemoteID(ctx context.Context, tag string) (int, error) {
  132. if id, ok := r.cacheGetTag(tag); ok {
  133. return id, nil
  134. }
  135. if err := r.refreshRemoteIDs(ctx); err != nil {
  136. return 0, err
  137. }
  138. if id, ok := r.cacheGetTag(tag); ok {
  139. return id, nil
  140. }
  141. return 0, fmt.Errorf("remote inbound with tag %q not found on node %s", tag, r.node.Name)
  142. }
  143. // cacheGetTag looks up a remote inbound id by tag, tolerating an n<id>- prefix
  144. // that lives on only one of the two panels: the node may carry the bare tag
  145. // while the central panel stores the prefixed form, or vice versa.
  146. func (r *Remote) cacheGetTag(tag string) (int, bool) {
  147. if id, ok := r.cacheGet(tag); ok {
  148. return id, true
  149. }
  150. prefix := fmt.Sprintf("n%d-", r.node.Id)
  151. if stripped, found := strings.CutPrefix(tag, prefix); found {
  152. return r.cacheGet(stripped)
  153. }
  154. return r.cacheGet(prefix + tag)
  155. }
  156. func (r *Remote) cacheGet(tag string) (int, bool) {
  157. r.mu.RLock()
  158. defer r.mu.RUnlock()
  159. id, ok := r.remoteIDByTag[tag]
  160. return id, ok
  161. }
  162. func (r *Remote) cacheSet(tag string, id int) {
  163. r.mu.Lock()
  164. defer r.mu.Unlock()
  165. r.remoteIDByTag[tag] = id
  166. }
  167. func (r *Remote) cacheDel(tag string) {
  168. r.mu.Lock()
  169. defer r.mu.Unlock()
  170. delete(r.remoteIDByTag, tag)
  171. }
  172. func (r *Remote) ListRemoteTags(ctx context.Context) ([]string, error) {
  173. if err := r.refreshRemoteIDs(ctx); err != nil {
  174. return nil, err
  175. }
  176. r.mu.RLock()
  177. defer r.mu.RUnlock()
  178. tags := make([]string, 0, len(r.remoteIDByTag))
  179. for tag := range r.remoteIDByTag {
  180. tags = append(tags, tag)
  181. }
  182. return tags, nil
  183. }
  184. func (r *Remote) refreshRemoteIDs(ctx context.Context) error {
  185. env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
  186. if err != nil {
  187. return err
  188. }
  189. var list []struct {
  190. Id int `json:"id"`
  191. Tag string `json:"tag"`
  192. }
  193. if err := json.Unmarshal(env.Obj, &list); err != nil {
  194. return fmt.Errorf("decode inbound list: %w", err)
  195. }
  196. next := make(map[string]int, len(list))
  197. for _, ib := range list {
  198. if ib.Tag == "" {
  199. continue
  200. }
  201. next[ib.Tag] = ib.Id
  202. }
  203. r.mu.Lock()
  204. r.remoteIDByTag = next
  205. r.mu.Unlock()
  206. return nil
  207. }
  208. func (r *Remote) AddInbound(ctx context.Context, ib *model.Inbound) error {
  209. payload := wireInbound(ib)
  210. env, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/add", payload)
  211. if err != nil {
  212. return err
  213. }
  214. var created struct {
  215. Id int `json:"id"`
  216. Tag string `json:"tag"`
  217. }
  218. if len(env.Obj) > 0 {
  219. if err := json.Unmarshal(env.Obj, &created); err == nil && created.Id > 0 && created.Tag != "" {
  220. r.cacheSet(created.Tag, created.Id)
  221. }
  222. }
  223. return nil
  224. }
  225. func (r *Remote) DelInbound(ctx context.Context, ib *model.Inbound) error {
  226. id, err := r.resolveRemoteID(ctx, ib.Tag)
  227. if err != nil {
  228. logger.Warning("remote DelInbound: tag", ib.Tag, "not found on", r.node.Name)
  229. return nil
  230. }
  231. if _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/del/"+strconv.Itoa(id), nil); err != nil {
  232. return err
  233. }
  234. r.cacheDel(ib.Tag)
  235. return nil
  236. }
  237. func (r *Remote) UpdateInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
  238. id, err := r.resolveRemoteID(ctx, oldIb.Tag)
  239. if err != nil {
  240. return r.AddInbound(ctx, newIb)
  241. }
  242. payload := wireInbound(newIb)
  243. if _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/update/"+strconv.Itoa(id), payload); err != nil {
  244. return err
  245. }
  246. if oldIb.Tag != newIb.Tag {
  247. r.cacheDel(oldIb.Tag)
  248. }
  249. r.cacheSet(newIb.Tag, id)
  250. return nil
  251. }
  252. func (r *Remote) AddUser(ctx context.Context, ib *model.Inbound, _ map[string]any) error {
  253. return r.UpdateInbound(ctx, ib, ib)
  254. }
  255. func (r *Remote) RemoveUser(ctx context.Context, ib *model.Inbound, _ string) error {
  256. return r.UpdateInbound(ctx, ib, ib)
  257. }
  258. func (r *Remote) AddClient(ctx context.Context, ib *model.Inbound, client model.Client) error {
  259. id, err := r.resolveRemoteID(ctx, ib.Tag)
  260. if err != nil {
  261. return fmt.Errorf("remote AddClient: resolve tag %q: %w", ib.Tag, err)
  262. }
  263. payload := map[string]any{
  264. "client": client,
  265. "inboundIds": []int{id},
  266. }
  267. if _, err := r.do(ctx, http.MethodPost, "panel/api/clients/add", payload); err != nil {
  268. return err
  269. }
  270. return nil
  271. }
  272. func (r *Remote) DeleteUser(ctx context.Context, ib *model.Inbound, email string) error {
  273. if email == "" {
  274. return nil
  275. }
  276. id, err := r.resolveRemoteID(ctx, ib.Tag)
  277. if err != nil {
  278. return nil
  279. }
  280. body := map[string]any{"inboundIds": []int{id}}
  281. _, err = r.do(ctx, http.MethodPost,
  282. "panel/api/clients/"+url.PathEscape(email)+"/detach", body)
  283. if err == nil {
  284. return nil
  285. }
  286. if strings.Contains(strings.ToLower(err.Error()), "not found") {
  287. return nil
  288. }
  289. return err
  290. }
  291. func (r *Remote) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, payload model.Client) error {
  292. if oldEmail == "" {
  293. oldEmail = payload.Email
  294. }
  295. id, err := r.resolveRemoteID(ctx, ib.Tag)
  296. if err != nil {
  297. return err
  298. }
  299. path := "panel/api/clients/update/" + url.PathEscape(oldEmail) +
  300. "?inboundIds=" + strconv.Itoa(id)
  301. if _, err := r.do(ctx, http.MethodPost, path, payload); err != nil {
  302. return err
  303. }
  304. return nil
  305. }
  306. func (r *Remote) RestartXray(ctx context.Context) error {
  307. _, err := r.do(ctx, http.MethodPost, "panel/api/server/restartXrayService", nil)
  308. return err
  309. }
  310. // UpdatePanel asks the node to run its own official self-updater (update.sh)
  311. // and restart onto the latest release. The node returns as soon as the job is
  312. // launched; the new version surfaces on the next heartbeat.
  313. func (r *Remote) UpdatePanel(ctx context.Context) error {
  314. _, err := r.do(ctx, http.MethodPost, "panel/api/server/updatePanel", nil)
  315. return err
  316. }
  317. // WebCertFiles holds a node's own web TLS certificate and key file paths.
  318. type WebCertFiles struct {
  319. WebCertFile string `json:"webCertFile"`
  320. WebKeyFile string `json:"webKeyFile"`
  321. }
  322. // GetWebCertFiles fetches the node's own web TLS certificate/key file paths so
  323. // the central panel can offer them as the "Set Cert from Panel" default for a
  324. // node-assigned inbound — those paths exist on the node, the central panel's
  325. // don't. See issue #4854.
  326. func (r *Remote) GetWebCertFiles(ctx context.Context) (*WebCertFiles, error) {
  327. env, err := r.do(ctx, http.MethodGet, "panel/api/server/getWebCertFiles", nil)
  328. if err != nil {
  329. return nil, err
  330. }
  331. var files WebCertFiles
  332. if err := json.Unmarshal(env.Obj, &files); err != nil {
  333. return nil, fmt.Errorf("decode web cert files: %w", err)
  334. }
  335. return &files, nil
  336. }
  337. // GetDescendants fetches the node's read-only summaries of the nodes IT
  338. // manages, so this panel can surface them as transitive sub-nodes in a chained
  339. // topology (#4983). Best-effort: an old-build node without the endpoint returns
  340. // an error the caller ignores.
  341. func (r *Remote) GetDescendants(ctx context.Context) ([]model.NodeSummary, error) {
  342. env, err := r.do(ctx, http.MethodGet, "panel/api/server/descendants", nil)
  343. if err != nil {
  344. return nil, err
  345. }
  346. var out []model.NodeSummary
  347. if len(env.Obj) > 0 {
  348. if err := json.Unmarshal(env.Obj, &out); err != nil {
  349. return nil, fmt.Errorf("decode descendants: %w", err)
  350. }
  351. }
  352. return out, nil
  353. }
  354. func (r *Remote) ResetClientTraffic(ctx context.Context, _ *model.Inbound, email string) error {
  355. _, err := r.do(ctx, http.MethodPost,
  356. "panel/api/clients/resetTraffic/"+url.PathEscape(email), nil)
  357. return err
  358. }
  359. func (r *Remote) ResetAllTraffics(ctx context.Context) error {
  360. _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/resetAllTraffics", nil)
  361. return err
  362. }
  363. func (r *Remote) ResetInboundTraffic(ctx context.Context, ib *model.Inbound) error {
  364. _, err := r.do(ctx, http.MethodPost, fmt.Sprintf("panel/api/inbounds/%d/resetTraffic", ib.Id), nil)
  365. return err
  366. }
  367. type TrafficSnapshot struct {
  368. Inbounds []*model.Inbound
  369. OnlineEmails []string
  370. // OnlineTree is the node's GUID-keyed online subtree (its own clients under
  371. // its panelGuid plus every descendant under theirs). Preferred over the flat
  372. // OnlineEmails so the master can attribute deeply nested clients to the real
  373. // node across a chain (#4983). Empty when the node is an old build without
  374. // the per-GUID endpoint — OnlineEmails is the fallback then.
  375. OnlineTree map[string][]string
  376. LastOnlineMap map[string]int64
  377. }
  378. func (r *Remote) FetchTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, error) {
  379. snap := &TrafficSnapshot{LastOnlineMap: map[string]int64{}}
  380. envList, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
  381. if err != nil {
  382. return nil, err
  383. }
  384. if err := json.Unmarshal(envList.Obj, &snap.Inbounds); err != nil {
  385. return nil, fmt.Errorf("decode inbound list: %w", err)
  386. }
  387. // Prefer the GUID-keyed subtree; fall back to the flat list only when the
  388. // node is an old build without the per-GUID endpoint (#4983).
  389. envTree, err := r.do(ctx, http.MethodPost, "panel/api/clients/onlinesByGuid", nil)
  390. if err == nil && len(envTree.Obj) > 0 {
  391. _ = json.Unmarshal(envTree.Obj, &snap.OnlineTree)
  392. }
  393. if len(snap.OnlineTree) == 0 {
  394. envOnlines, err := r.do(ctx, http.MethodPost, "panel/api/clients/onlines", nil)
  395. if err != nil {
  396. logger.Warning("remote", r.node.Name, "onlines fetch failed:", err)
  397. } else if len(envOnlines.Obj) > 0 {
  398. _ = json.Unmarshal(envOnlines.Obj, &snap.OnlineEmails)
  399. }
  400. }
  401. envLastOnline, err := r.do(ctx, http.MethodPost, "panel/api/clients/lastOnline", nil)
  402. if err != nil {
  403. logger.Warning("remote", r.node.Name, "lastOnline fetch failed:", err)
  404. } else if len(envLastOnline.Obj) > 0 {
  405. _ = json.Unmarshal(envLastOnline.Obj, &snap.LastOnlineMap)
  406. }
  407. return snap, nil
  408. }
  409. // PushGlobalClientTraffics sends this panel's aggregated per-client usage to
  410. // the node, tagged with this panel's GUID so the node keeps one row per
  411. // pushing master. Display/enforcement input on the node only — the node never
  412. // folds these into the counters it reports back, so this panel's (and any
  413. // other master's) delta accounting over the node snapshot stays intact.
  414. func (r *Remote) PushGlobalClientTraffics(ctx context.Context, masterGuid string, traffics []*xray.ClientTraffic) error {
  415. payload := map[string]any{
  416. "masterGuid": masterGuid,
  417. "traffics": traffics,
  418. }
  419. _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/pushClientTraffics", payload)
  420. return err
  421. }
  422. func wireInbound(ib *model.Inbound) url.Values {
  423. v := url.Values{}
  424. v.Set("total", strconv.FormatInt(ib.Total, 10))
  425. v.Set("remark", ib.Remark)
  426. v.Set("enable", strconv.FormatBool(ib.Enable))
  427. v.Set("expiryTime", strconv.FormatInt(ib.ExpiryTime, 10))
  428. v.Set("listen", ib.Listen)
  429. v.Set("port", strconv.Itoa(ib.Port))
  430. v.Set("protocol", string(ib.Protocol))
  431. v.Set("settings", ib.Settings)
  432. v.Set("streamSettings", sanitizeStreamSettingsForRemote(ib.StreamSettings))
  433. v.Set("tag", ib.Tag)
  434. v.Set("sniffing", ib.Sniffing)
  435. shareAddrStrategy := strings.TrimSpace(ib.ShareAddrStrategy)
  436. switch shareAddrStrategy {
  437. case "listen", "custom":
  438. default:
  439. shareAddrStrategy = "node"
  440. }
  441. v.Set("shareAddrStrategy", shareAddrStrategy)
  442. v.Set("shareAddr", ib.ShareAddr)
  443. if ib.TrafficReset != "" {
  444. v.Set("trafficReset", ib.TrafficReset)
  445. }
  446. return v
  447. }
  448. // sanitizeStreamSettingsForRemote strips file-based TLS certificate paths
  449. // from the StreamSettings before sending to a remote node, but ONLY when
  450. // inline certificate content (certificate / key) is also present in the same
  451. // entry. In that case the file paths are redundant and stripping them avoids
  452. // confusion when the central panel's local paths don't exist on the remote.
  453. //
  454. // When a certificate entry contains ONLY file paths (no inline content) the
  455. // paths are left untouched: the user explicitly entered paths that exist on
  456. // the remote node's filesystem, and removing them would leave Xray with TLS
  457. // configured but no certificate, causing Xray to crash on the remote node.
  458. func sanitizeStreamSettingsForRemote(streamSettings string) string {
  459. if streamSettings == "" {
  460. return streamSettings
  461. }
  462. var stream map[string]any
  463. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  464. return streamSettings
  465. }
  466. tlsSettings, ok := stream["tlsSettings"].(map[string]any)
  467. if !ok {
  468. return streamSettings
  469. }
  470. certificates, ok := tlsSettings["certificates"].([]any)
  471. if !ok {
  472. return streamSettings
  473. }
  474. changed := false
  475. for _, cert := range certificates {
  476. c, ok := cert.(map[string]any)
  477. if !ok {
  478. continue
  479. }
  480. // Only strip file paths when inline content is present so that the
  481. // remote Xray still has a valid certificate to use.
  482. hasCertFile := c["certificateFile"] != nil && c["certificateFile"] != ""
  483. hasKeyFile := c["keyFile"] != nil && c["keyFile"] != ""
  484. hasCertInline := isNonEmptySlice(c["certificate"])
  485. hasKeyInline := isNonEmptySlice(c["key"])
  486. if hasCertFile && hasCertInline {
  487. delete(c, "certificateFile")
  488. changed = true
  489. }
  490. if hasKeyFile && hasKeyInline {
  491. delete(c, "keyFile")
  492. changed = true
  493. }
  494. }
  495. if !changed {
  496. return streamSettings
  497. }
  498. out, err := json.Marshal(stream)
  499. if err != nil {
  500. return streamSettings
  501. }
  502. return string(out)
  503. }
  504. // isNonEmptySlice reports whether v is a non-nil, non-empty JSON array value.
  505. func isNonEmptySlice(v any) bool {
  506. s, ok := v.([]any)
  507. return ok && len(s) > 0
  508. }
  509. func (r *Remote) FetchAllClientIps(ctx context.Context) ([]model.InboundClientIps, error) {
  510. env, err := r.do(ctx, http.MethodGet, "panel/api/server/clientIps", nil)
  511. if err != nil {
  512. return nil, err
  513. }
  514. var ips []model.InboundClientIps
  515. if len(env.Obj) > 0 {
  516. if err := json.Unmarshal(env.Obj, &ips); err != nil {
  517. return nil, fmt.Errorf("decode client ips: %w", err)
  518. }
  519. }
  520. return ips, nil
  521. }
  522. func (r *Remote) PushAllClientIps(ctx context.Context, ips []model.InboundClientIps) error {
  523. _, err := r.do(ctx, http.MethodPost, "panel/api/server/clientIps", ips)
  524. return err
  525. }