remote.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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.cacheGet(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.cacheGet(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. func (r *Remote) cacheGet(tag string) (int, bool) {
  143. r.mu.RLock()
  144. defer r.mu.RUnlock()
  145. id, ok := r.remoteIDByTag[tag]
  146. return id, ok
  147. }
  148. func (r *Remote) cacheSet(tag string, id int) {
  149. r.mu.Lock()
  150. defer r.mu.Unlock()
  151. r.remoteIDByTag[tag] = id
  152. }
  153. func (r *Remote) cacheDel(tag string) {
  154. r.mu.Lock()
  155. defer r.mu.Unlock()
  156. delete(r.remoteIDByTag, tag)
  157. }
  158. func (r *Remote) refreshRemoteIDs(ctx context.Context) error {
  159. env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
  160. if err != nil {
  161. return err
  162. }
  163. var list []struct {
  164. Id int `json:"id"`
  165. Tag string `json:"tag"`
  166. }
  167. if err := json.Unmarshal(env.Obj, &list); err != nil {
  168. return fmt.Errorf("decode inbound list: %w", err)
  169. }
  170. next := make(map[string]int, len(list))
  171. for _, ib := range list {
  172. if ib.Tag == "" {
  173. continue
  174. }
  175. next[ib.Tag] = ib.Id
  176. }
  177. r.mu.Lock()
  178. r.remoteIDByTag = next
  179. r.mu.Unlock()
  180. return nil
  181. }
  182. func (r *Remote) AddInbound(ctx context.Context, ib *model.Inbound) error {
  183. payload := wireInbound(ib)
  184. env, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/add", payload)
  185. if err != nil {
  186. return err
  187. }
  188. var created struct {
  189. Id int `json:"id"`
  190. Tag string `json:"tag"`
  191. }
  192. if len(env.Obj) > 0 {
  193. if err := json.Unmarshal(env.Obj, &created); err == nil && created.Id > 0 && created.Tag != "" {
  194. r.cacheSet(created.Tag, created.Id)
  195. }
  196. }
  197. return nil
  198. }
  199. func (r *Remote) DelInbound(ctx context.Context, ib *model.Inbound) error {
  200. id, err := r.resolveRemoteID(ctx, ib.Tag)
  201. if err != nil {
  202. logger.Warning("remote DelInbound: tag", ib.Tag, "not found on", r.node.Name)
  203. return nil
  204. }
  205. if _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/del/"+strconv.Itoa(id), nil); err != nil {
  206. return err
  207. }
  208. r.cacheDel(ib.Tag)
  209. return nil
  210. }
  211. func (r *Remote) UpdateInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
  212. id, err := r.resolveRemoteID(ctx, oldIb.Tag)
  213. if err != nil {
  214. return r.AddInbound(ctx, newIb)
  215. }
  216. payload := wireInbound(newIb)
  217. if _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/update/"+strconv.Itoa(id), payload); err != nil {
  218. return err
  219. }
  220. if oldIb.Tag != newIb.Tag {
  221. r.cacheDel(oldIb.Tag)
  222. }
  223. r.cacheSet(newIb.Tag, id)
  224. return nil
  225. }
  226. func (r *Remote) AddUser(ctx context.Context, ib *model.Inbound, _ map[string]any) error {
  227. return r.UpdateInbound(ctx, ib, ib)
  228. }
  229. func (r *Remote) RemoveUser(ctx context.Context, ib *model.Inbound, _ string) error {
  230. return r.UpdateInbound(ctx, ib, ib)
  231. }
  232. func (r *Remote) AddClient(ctx context.Context, ib *model.Inbound, client model.Client) error {
  233. id, err := r.resolveRemoteID(ctx, ib.Tag)
  234. if err != nil {
  235. return fmt.Errorf("remote AddClient: resolve tag %q: %w", ib.Tag, err)
  236. }
  237. payload := map[string]any{
  238. "client": client,
  239. "inboundIds": []int{id},
  240. }
  241. if _, err := r.do(ctx, http.MethodPost, "panel/api/clients/add", payload); err != nil {
  242. return err
  243. }
  244. return nil
  245. }
  246. // DeleteUser is idempotent: master's per-inbound Delete loop may call it
  247. // multiple times for the same node, and "not found" on the follow-ups is
  248. // the expected success path.
  249. func (r *Remote) DeleteUser(ctx context.Context, _ *model.Inbound, email string) error {
  250. if email == "" {
  251. return nil
  252. }
  253. _, err := r.do(ctx, http.MethodPost,
  254. "panel/api/clients/del/"+url.PathEscape(email), nil)
  255. if err == nil {
  256. return nil
  257. }
  258. if strings.Contains(strings.ToLower(err.Error()), "not found") {
  259. return nil
  260. }
  261. return err
  262. }
  263. func (r *Remote) UpdateUser(ctx context.Context, _ *model.Inbound, oldEmail string, payload model.Client) error {
  264. if oldEmail == "" {
  265. oldEmail = payload.Email
  266. }
  267. if _, err := r.do(ctx, http.MethodPost,
  268. "panel/api/clients/update/"+url.PathEscape(oldEmail), payload); err != nil {
  269. return err
  270. }
  271. return nil
  272. }
  273. func (r *Remote) RestartXray(ctx context.Context) error {
  274. _, err := r.do(ctx, http.MethodPost, "panel/api/server/restartXrayService", nil)
  275. return err
  276. }
  277. func (r *Remote) ResetClientTraffic(ctx context.Context, _ *model.Inbound, email string) error {
  278. _, err := r.do(ctx, http.MethodPost,
  279. "panel/api/clients/resetTraffic/"+url.PathEscape(email), nil)
  280. return err
  281. }
  282. func (r *Remote) ResetAllTraffics(ctx context.Context) error {
  283. _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/resetAllTraffics", nil)
  284. return err
  285. }
  286. type TrafficSnapshot struct {
  287. Inbounds []*model.Inbound
  288. OnlineEmails []string
  289. LastOnlineMap map[string]int64
  290. }
  291. func (r *Remote) FetchTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, error) {
  292. snap := &TrafficSnapshot{LastOnlineMap: map[string]int64{}}
  293. envList, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
  294. if err != nil {
  295. return nil, err
  296. }
  297. if err := json.Unmarshal(envList.Obj, &snap.Inbounds); err != nil {
  298. return nil, fmt.Errorf("decode inbound list: %w", err)
  299. }
  300. envOnlines, err := r.do(ctx, http.MethodPost, "panel/api/clients/onlines", nil)
  301. if err != nil {
  302. logger.Warning("remote", r.node.Name, "onlines fetch failed:", err)
  303. } else if len(envOnlines.Obj) > 0 {
  304. _ = json.Unmarshal(envOnlines.Obj, &snap.OnlineEmails)
  305. }
  306. envLastOnline, err := r.do(ctx, http.MethodPost, "panel/api/clients/lastOnline", nil)
  307. if err != nil {
  308. logger.Warning("remote", r.node.Name, "lastOnline fetch failed:", err)
  309. } else if len(envLastOnline.Obj) > 0 {
  310. _ = json.Unmarshal(envLastOnline.Obj, &snap.LastOnlineMap)
  311. }
  312. return snap, nil
  313. }
  314. func wireInbound(ib *model.Inbound) url.Values {
  315. v := url.Values{}
  316. v.Set("total", strconv.FormatInt(ib.Total, 10))
  317. v.Set("remark", ib.Remark)
  318. v.Set("enable", strconv.FormatBool(ib.Enable))
  319. v.Set("expiryTime", strconv.FormatInt(ib.ExpiryTime, 10))
  320. v.Set("listen", ib.Listen)
  321. v.Set("port", strconv.Itoa(ib.Port))
  322. v.Set("protocol", string(ib.Protocol))
  323. v.Set("settings", ib.Settings)
  324. v.Set("streamSettings", sanitizeStreamSettingsForRemote(ib.StreamSettings))
  325. v.Set("tag", ib.Tag)
  326. v.Set("sniffing", ib.Sniffing)
  327. if ib.TrafficReset != "" {
  328. v.Set("trafficReset", ib.TrafficReset)
  329. }
  330. return v
  331. }
  332. // sanitizeStreamSettingsForRemote strips file-based TLS certificate paths
  333. // from the StreamSettings before sending to a remote node, but ONLY when
  334. // inline certificate content (certificate / key) is also present in the same
  335. // entry. In that case the file paths are redundant and stripping them avoids
  336. // confusion when the central panel's local paths don't exist on the remote.
  337. //
  338. // When a certificate entry contains ONLY file paths (no inline content) the
  339. // paths are left untouched: the user explicitly entered paths that exist on
  340. // the remote node's filesystem, and removing them would leave Xray with TLS
  341. // configured but no certificate, causing Xray to crash on the remote node.
  342. func sanitizeStreamSettingsForRemote(streamSettings string) string {
  343. if streamSettings == "" {
  344. return streamSettings
  345. }
  346. var stream map[string]any
  347. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  348. return streamSettings
  349. }
  350. tlsSettings, ok := stream["tlsSettings"].(map[string]any)
  351. if !ok {
  352. return streamSettings
  353. }
  354. certificates, ok := tlsSettings["certificates"].([]any)
  355. if !ok {
  356. return streamSettings
  357. }
  358. changed := false
  359. for _, cert := range certificates {
  360. c, ok := cert.(map[string]any)
  361. if !ok {
  362. continue
  363. }
  364. // Only strip file paths when inline content is present so that the
  365. // remote Xray still has a valid certificate to use.
  366. hasCertFile := c["certificateFile"] != nil && c["certificateFile"] != ""
  367. hasKeyFile := c["keyFile"] != nil && c["keyFile"] != ""
  368. hasCertInline := isNonEmptySlice(c["certificate"])
  369. hasKeyInline := isNonEmptySlice(c["key"])
  370. if hasCertFile && hasCertInline {
  371. delete(c, "certificateFile")
  372. changed = true
  373. }
  374. if hasKeyFile && hasKeyInline {
  375. delete(c, "keyFile")
  376. changed = true
  377. }
  378. }
  379. if !changed {
  380. return streamSettings
  381. }
  382. out, err := json.Marshal(stream)
  383. if err != nil {
  384. return streamSettings
  385. }
  386. return string(out)
  387. }
  388. // isNonEmptySlice reports whether v is a non-nil, non-empty JSON array value.
  389. func isNonEmptySlice(v any) bool {
  390. s, ok := v.([]any)
  391. return ok && len(s) > 0
  392. }