remote.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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) RestartXray(ctx context.Context) error {
  233. _, err := r.do(ctx, http.MethodPost, "panel/api/server/restartXrayService", nil)
  234. return err
  235. }
  236. func (r *Remote) ResetClientTraffic(ctx context.Context, ib *model.Inbound, email string) error {
  237. id, err := r.resolveRemoteID(ctx, ib.Tag)
  238. if err != nil {
  239. logger.Warning("remote ResetClientTraffic: tag", ib.Tag, "not found on", r.node.Name)
  240. return nil
  241. }
  242. _, err = r.do(ctx, http.MethodPost,
  243. fmt.Sprintf("panel/api/inbounds/%d/resetClientTraffic/%s", id, url.PathEscape(email)),
  244. nil)
  245. return err
  246. }
  247. func (r *Remote) ResetInboundClientTraffics(ctx context.Context, ib *model.Inbound) error {
  248. id, err := r.resolveRemoteID(ctx, ib.Tag)
  249. if err != nil {
  250. logger.Warning("remote ResetInboundClientTraffics: tag", ib.Tag, "not found on", r.node.Name)
  251. return nil
  252. }
  253. _, err = r.do(ctx, http.MethodPost,
  254. fmt.Sprintf("panel/api/inbounds/resetAllClientTraffics/%d", id), nil)
  255. return err
  256. }
  257. func (r *Remote) ResetAllTraffics(ctx context.Context) error {
  258. _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/resetAllTraffics", nil)
  259. return err
  260. }
  261. type TrafficSnapshot struct {
  262. Inbounds []*model.Inbound
  263. OnlineEmails []string
  264. LastOnlineMap map[string]int64
  265. }
  266. func (r *Remote) FetchTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, error) {
  267. snap := &TrafficSnapshot{LastOnlineMap: map[string]int64{}}
  268. envList, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
  269. if err != nil {
  270. return nil, err
  271. }
  272. if err := json.Unmarshal(envList.Obj, &snap.Inbounds); err != nil {
  273. return nil, fmt.Errorf("decode inbound list: %w", err)
  274. }
  275. envOnlines, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/onlines", nil)
  276. if err != nil {
  277. logger.Warning("remote", r.node.Name, "onlines fetch failed:", err)
  278. } else if len(envOnlines.Obj) > 0 {
  279. _ = json.Unmarshal(envOnlines.Obj, &snap.OnlineEmails)
  280. }
  281. envLastOnline, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/lastOnline", nil)
  282. if err != nil {
  283. logger.Warning("remote", r.node.Name, "lastOnline fetch failed:", err)
  284. } else if len(envLastOnline.Obj) > 0 {
  285. _ = json.Unmarshal(envLastOnline.Obj, &snap.LastOnlineMap)
  286. }
  287. return snap, nil
  288. }
  289. func wireInbound(ib *model.Inbound) url.Values {
  290. v := url.Values{}
  291. v.Set("total", strconv.FormatInt(ib.Total, 10))
  292. v.Set("remark", ib.Remark)
  293. v.Set("enable", strconv.FormatBool(ib.Enable))
  294. v.Set("expiryTime", strconv.FormatInt(ib.ExpiryTime, 10))
  295. v.Set("listen", ib.Listen)
  296. v.Set("port", strconv.Itoa(ib.Port))
  297. v.Set("protocol", string(ib.Protocol))
  298. v.Set("settings", ib.Settings)
  299. v.Set("streamSettings", sanitizeStreamSettingsForRemote(ib.StreamSettings))
  300. v.Set("tag", ib.Tag)
  301. v.Set("sniffing", ib.Sniffing)
  302. if ib.TrafficReset != "" {
  303. v.Set("trafficReset", ib.TrafficReset)
  304. }
  305. return v
  306. }
  307. // sanitizeStreamSettingsForRemote strips file-based TLS certificate paths
  308. // from the StreamSettings before sending to a remote node. File paths
  309. // (certificateFile / keyFile) are local to the main panel's filesystem
  310. // and will cause Xray on the remote node to crash if they don't exist there.
  311. // Inline certificate content (certificate / key) is kept intact.
  312. func sanitizeStreamSettingsForRemote(streamSettings string) string {
  313. if streamSettings == "" {
  314. return streamSettings
  315. }
  316. var stream map[string]any
  317. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  318. return streamSettings
  319. }
  320. tlsSettings, ok := stream["tlsSettings"].(map[string]any)
  321. if !ok {
  322. return streamSettings
  323. }
  324. certificates, ok := tlsSettings["certificates"].([]any)
  325. if !ok {
  326. return streamSettings
  327. }
  328. for _, cert := range certificates {
  329. c, ok := cert.(map[string]any)
  330. if !ok {
  331. continue
  332. }
  333. delete(c, "certificateFile")
  334. delete(c, "keyFile")
  335. }
  336. out, err := json.Marshal(stream)
  337. if err != nil {
  338. return streamSettings
  339. }
  340. return string(out)
  341. }