1
0

remote.go 17 KB

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