1
0

remote.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. package runtime
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "net/url"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/mhsanaei/3x-ui/v3/database/model"
  16. "github.com/mhsanaei/3x-ui/v3/logger"
  17. )
  18. const remoteHTTPTimeout = 10 * time.Second
  19. var remoteHTTPClient = &http.Client{
  20. Transport: &http.Transport{
  21. MaxIdleConns: 64,
  22. MaxIdleConnsPerHost: 4,
  23. IdleConnTimeout: 60 * time.Second,
  24. },
  25. }
  26. type envelope struct {
  27. Success bool `json:"success"`
  28. Msg string `json:"msg"`
  29. Obj json.RawMessage `json:"obj"`
  30. }
  31. type Remote struct {
  32. node *model.Node
  33. mu sync.RWMutex
  34. remoteIDByTag map[string]int
  35. }
  36. func NewRemote(n *model.Node) *Remote {
  37. return &Remote{
  38. node: n,
  39. remoteIDByTag: make(map[string]int),
  40. }
  41. }
  42. func (r *Remote) Name() string { return "node:" + r.node.Name }
  43. func (r *Remote) baseURL() string {
  44. bp := r.node.BasePath
  45. if bp == "" {
  46. bp = "/"
  47. }
  48. if !strings.HasSuffix(bp, "/") {
  49. bp += "/"
  50. }
  51. return fmt.Sprintf("%s://%s:%d%s", r.node.Scheme, r.node.Address, r.node.Port, bp)
  52. }
  53. func (r *Remote) do(ctx context.Context, method, path string, body any) (*envelope, error) {
  54. if r.node.ApiToken == "" {
  55. return nil, errors.New("node has no API token configured")
  56. }
  57. target := r.baseURL() + strings.TrimPrefix(path, "/")
  58. var (
  59. reqBody io.Reader
  60. contentType string
  61. )
  62. switch b := body.(type) {
  63. case nil:
  64. case url.Values:
  65. reqBody = strings.NewReader(b.Encode())
  66. contentType = "application/x-www-form-urlencoded"
  67. default:
  68. buf, err := json.Marshal(b)
  69. if err != nil {
  70. return nil, fmt.Errorf("marshal body: %w", err)
  71. }
  72. reqBody = bytes.NewReader(buf)
  73. contentType = "application/json"
  74. }
  75. cctx, cancel := context.WithTimeout(ctx, remoteHTTPTimeout)
  76. defer cancel()
  77. req, err := http.NewRequestWithContext(cctx, method, target, reqBody)
  78. if err != nil {
  79. return nil, err
  80. }
  81. req.Header.Set("Authorization", "Bearer "+r.node.ApiToken)
  82. req.Header.Set("Accept", "application/json")
  83. if contentType != "" {
  84. req.Header.Set("Content-Type", contentType)
  85. }
  86. resp, err := remoteHTTPClient.Do(req)
  87. if err != nil {
  88. return nil, fmt.Errorf("%s %s: %w", method, path, err)
  89. }
  90. defer resp.Body.Close()
  91. raw, err := io.ReadAll(resp.Body)
  92. if err != nil {
  93. return nil, fmt.Errorf("read body: %w", err)
  94. }
  95. if resp.StatusCode != http.StatusOK {
  96. return nil, fmt.Errorf("%s %s: HTTP %d", method, path, resp.StatusCode)
  97. }
  98. var env envelope
  99. if err := json.Unmarshal(raw, &env); err != nil {
  100. return nil, fmt.Errorf("decode envelope: %w", err)
  101. }
  102. if !env.Success {
  103. return &env, fmt.Errorf("remote: %s", env.Msg)
  104. }
  105. return &env, nil
  106. }
  107. func (r *Remote) resolveRemoteID(ctx context.Context, tag string) (int, error) {
  108. if id, ok := r.cacheGet(tag); ok {
  109. return id, nil
  110. }
  111. if err := r.refreshRemoteIDs(ctx); err != nil {
  112. return 0, err
  113. }
  114. if id, ok := r.cacheGet(tag); ok {
  115. return id, nil
  116. }
  117. return 0, fmt.Errorf("remote inbound with tag %q not found on node %s", tag, r.node.Name)
  118. }
  119. func (r *Remote) cacheGet(tag string) (int, bool) {
  120. r.mu.RLock()
  121. defer r.mu.RUnlock()
  122. id, ok := r.remoteIDByTag[tag]
  123. return id, ok
  124. }
  125. func (r *Remote) cacheSet(tag string, id int) {
  126. r.mu.Lock()
  127. defer r.mu.Unlock()
  128. r.remoteIDByTag[tag] = id
  129. }
  130. func (r *Remote) cacheDel(tag string) {
  131. r.mu.Lock()
  132. defer r.mu.Unlock()
  133. delete(r.remoteIDByTag, tag)
  134. }
  135. func (r *Remote) refreshRemoteIDs(ctx context.Context) error {
  136. env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
  137. if err != nil {
  138. return err
  139. }
  140. var list []struct {
  141. Id int `json:"id"`
  142. Tag string `json:"tag"`
  143. }
  144. if err := json.Unmarshal(env.Obj, &list); err != nil {
  145. return fmt.Errorf("decode inbound list: %w", err)
  146. }
  147. next := make(map[string]int, len(list))
  148. for _, ib := range list {
  149. if ib.Tag == "" {
  150. continue
  151. }
  152. next[ib.Tag] = ib.Id
  153. }
  154. r.mu.Lock()
  155. r.remoteIDByTag = next
  156. r.mu.Unlock()
  157. return nil
  158. }
  159. func (r *Remote) AddInbound(ctx context.Context, ib *model.Inbound) error {
  160. payload := wireInbound(ib)
  161. env, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/add", payload)
  162. if err != nil {
  163. return err
  164. }
  165. var created struct {
  166. Id int `json:"id"`
  167. Tag string `json:"tag"`
  168. }
  169. if len(env.Obj) > 0 {
  170. if err := json.Unmarshal(env.Obj, &created); err == nil && created.Id > 0 && created.Tag != "" {
  171. r.cacheSet(created.Tag, created.Id)
  172. }
  173. }
  174. return nil
  175. }
  176. func (r *Remote) DelInbound(ctx context.Context, ib *model.Inbound) error {
  177. id, err := r.resolveRemoteID(ctx, ib.Tag)
  178. if err != nil {
  179. logger.Warning("remote DelInbound: tag", ib.Tag, "not found on", r.node.Name)
  180. return nil
  181. }
  182. if _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/del/"+strconv.Itoa(id), nil); err != nil {
  183. return err
  184. }
  185. r.cacheDel(ib.Tag)
  186. return nil
  187. }
  188. func (r *Remote) UpdateInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
  189. id, err := r.resolveRemoteID(ctx, oldIb.Tag)
  190. if err != nil {
  191. return r.AddInbound(ctx, newIb)
  192. }
  193. payload := wireInbound(newIb)
  194. if _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/update/"+strconv.Itoa(id), payload); err != nil {
  195. return err
  196. }
  197. if oldIb.Tag != newIb.Tag {
  198. r.cacheDel(oldIb.Tag)
  199. }
  200. r.cacheSet(newIb.Tag, id)
  201. return nil
  202. }
  203. func (r *Remote) AddUser(ctx context.Context, ib *model.Inbound, _ map[string]any) error {
  204. return r.UpdateInbound(ctx, ib, ib)
  205. }
  206. func (r *Remote) RemoveUser(ctx context.Context, ib *model.Inbound, _ string) error {
  207. return r.UpdateInbound(ctx, ib, ib)
  208. }
  209. func (r *Remote) RestartXray(ctx context.Context) error {
  210. _, err := r.do(ctx, http.MethodPost, "panel/api/server/restartXrayService", nil)
  211. return err
  212. }
  213. func (r *Remote) ResetClientTraffic(ctx context.Context, ib *model.Inbound, email string) error {
  214. id, err := r.resolveRemoteID(ctx, ib.Tag)
  215. if err != nil {
  216. logger.Warning("remote ResetClientTraffic: tag", ib.Tag, "not found on", r.node.Name)
  217. return nil
  218. }
  219. _, err = r.do(ctx, http.MethodPost,
  220. fmt.Sprintf("panel/api/inbounds/%d/resetClientTraffic/%s", id, url.PathEscape(email)),
  221. nil)
  222. return err
  223. }
  224. func (r *Remote) ResetInboundClientTraffics(ctx context.Context, ib *model.Inbound) error {
  225. id, err := r.resolveRemoteID(ctx, ib.Tag)
  226. if err != nil {
  227. logger.Warning("remote ResetInboundClientTraffics: tag", ib.Tag, "not found on", r.node.Name)
  228. return nil
  229. }
  230. _, err = r.do(ctx, http.MethodPost,
  231. fmt.Sprintf("panel/api/inbounds/resetAllClientTraffics/%d", id), nil)
  232. return err
  233. }
  234. func (r *Remote) ResetAllTraffics(ctx context.Context) error {
  235. _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/resetAllTraffics", nil)
  236. return err
  237. }
  238. type TrafficSnapshot struct {
  239. Inbounds []*model.Inbound
  240. OnlineEmails []string
  241. LastOnlineMap map[string]int64
  242. }
  243. func (r *Remote) FetchTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, error) {
  244. snap := &TrafficSnapshot{LastOnlineMap: map[string]int64{}}
  245. envList, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
  246. if err != nil {
  247. return nil, err
  248. }
  249. if err := json.Unmarshal(envList.Obj, &snap.Inbounds); err != nil {
  250. return nil, fmt.Errorf("decode inbound list: %w", err)
  251. }
  252. envOnlines, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/onlines", nil)
  253. if err != nil {
  254. logger.Warning("remote", r.node.Name, "onlines fetch failed:", err)
  255. } else if len(envOnlines.Obj) > 0 {
  256. _ = json.Unmarshal(envOnlines.Obj, &snap.OnlineEmails)
  257. }
  258. envLastOnline, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/lastOnline", nil)
  259. if err != nil {
  260. logger.Warning("remote", r.node.Name, "lastOnline fetch failed:", err)
  261. } else if len(envLastOnline.Obj) > 0 {
  262. _ = json.Unmarshal(envLastOnline.Obj, &snap.LastOnlineMap)
  263. }
  264. return snap, nil
  265. }
  266. func wireInbound(ib *model.Inbound) url.Values {
  267. v := url.Values{}
  268. v.Set("total", strconv.FormatInt(ib.Total, 10))
  269. v.Set("remark", ib.Remark)
  270. v.Set("enable", strconv.FormatBool(ib.Enable))
  271. v.Set("expiryTime", strconv.FormatInt(ib.ExpiryTime, 10))
  272. v.Set("listen", ib.Listen)
  273. v.Set("port", strconv.Itoa(ib.Port))
  274. v.Set("protocol", string(ib.Protocol))
  275. v.Set("settings", ib.Settings)
  276. v.Set("streamSettings", ib.StreamSettings)
  277. v.Set("tag", ib.Tag)
  278. v.Set("sniffing", ib.Sniffing)
  279. if ib.TrafficReset != "" {
  280. v.Set("trafficReset", ib.TrafficReset)
  281. }
  282. return v
  283. }