1
0

remote.go 13 KB

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