api.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. // Package xray provides integration with the Xray proxy core.
  2. // It includes API client functionality, configuration management, traffic monitoring,
  3. // and process control for Xray instances.
  4. package xray
  5. import (
  6. "context"
  7. "encoding/json"
  8. "fmt"
  9. "math"
  10. "net"
  11. "os"
  12. "path/filepath"
  13. "regexp"
  14. "strings"
  15. "time"
  16. "github.com/mhsanaei/3x-ui/v3/internal/config"
  17. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  18. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  19. "github.com/xtls/xray-core/app/proxyman/command"
  20. routerService "github.com/xtls/xray-core/app/router/command"
  21. statsService "github.com/xtls/xray-core/app/stats/command"
  22. xnet "github.com/xtls/xray-core/common/net"
  23. "github.com/xtls/xray-core/common/protocol"
  24. "github.com/xtls/xray-core/common/serial"
  25. "github.com/xtls/xray-core/infra/conf"
  26. hysteriaAccount "github.com/xtls/xray-core/proxy/hysteria/account"
  27. "github.com/xtls/xray-core/proxy/shadowsocks"
  28. "github.com/xtls/xray-core/proxy/shadowsocks_2022"
  29. "github.com/xtls/xray-core/proxy/trojan"
  30. "github.com/xtls/xray-core/proxy/vless"
  31. "github.com/xtls/xray-core/proxy/vmess"
  32. "google.golang.org/grpc"
  33. "google.golang.org/grpc/codes"
  34. "google.golang.org/grpc/credentials/insecure"
  35. "google.golang.org/grpc/status"
  36. )
  37. // Compiled once at package load: GetTraffic runs on every traffic-stats tick,
  38. // so recompiling these per call is wasted work.
  39. var (
  40. trafficRegex = regexp.MustCompile(`(inbound|outbound)>>>([^>]+)>>>traffic>>>(downlink|uplink)`)
  41. clientTrafficRegex = regexp.MustCompile(`user>>>([^>]+)>>>traffic>>>(downlink|uplink)`)
  42. )
  43. // XrayAPI is a gRPC client for managing Xray core configuration, inbounds, outbounds, and statistics.
  44. type XrayAPI struct {
  45. HandlerServiceClient *command.HandlerServiceClient
  46. StatsServiceClient *statsService.StatsServiceClient
  47. RoutingServiceClient *routerService.RoutingServiceClient
  48. grpcClient *grpc.ClientConn
  49. isConnected bool
  50. StatsLastValues map[string]int64
  51. }
  52. func getRequiredUserString(user map[string]any, key string) (string, error) {
  53. value, ok := user[key]
  54. if !ok || value == nil {
  55. return "", fmt.Errorf("missing required user field %q", key)
  56. }
  57. strValue, ok := value.(string)
  58. if !ok {
  59. return "", fmt.Errorf("invalid type for user field %q: %T", key, value)
  60. }
  61. return strValue, nil
  62. }
  63. func getOptionalUserString(user map[string]any, key string) (string, error) {
  64. value, ok := user[key]
  65. if !ok || value == nil {
  66. return "", nil
  67. }
  68. strValue, ok := value.(string)
  69. if !ok {
  70. return "", fmt.Errorf("invalid type for user field %q: %T", key, value)
  71. }
  72. return strValue, nil
  73. }
  74. // Init connects to the Xray API server and initializes handler and stats service clients.
  75. func (x *XrayAPI) Init(apiPort int) error {
  76. if apiPort <= 0 || apiPort > math.MaxUint16 {
  77. return fmt.Errorf("invalid Xray API port: %d", apiPort)
  78. }
  79. addr := fmt.Sprintf("127.0.0.1:%d", apiPort)
  80. conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
  81. if err != nil {
  82. return fmt.Errorf("failed to connect to Xray API: %w", err)
  83. }
  84. x.grpcClient = conn
  85. x.isConnected = true
  86. if x.StatsLastValues == nil {
  87. x.StatsLastValues = make(map[string]int64)
  88. }
  89. hsClient := command.NewHandlerServiceClient(conn)
  90. ssClient := statsService.NewStatsServiceClient(conn)
  91. rsClient := routerService.NewRoutingServiceClient(conn)
  92. x.HandlerServiceClient = &hsClient
  93. x.StatsServiceClient = &ssClient
  94. x.RoutingServiceClient = &rsClient
  95. return nil
  96. }
  97. // Close closes the gRPC connection and resets the XrayAPI client state.
  98. func (x *XrayAPI) Close() {
  99. if x.grpcClient != nil {
  100. x.grpcClient.Close()
  101. }
  102. x.HandlerServiceClient = nil
  103. x.StatsServiceClient = nil
  104. x.RoutingServiceClient = nil
  105. x.isConnected = false
  106. }
  107. // AddInbound adds a new inbound configuration to the Xray core via gRPC.
  108. func (x *XrayAPI) AddInbound(inbound []byte) error {
  109. client := *x.HandlerServiceClient
  110. conf := new(conf.InboundDetourConfig)
  111. err := json.Unmarshal(inbound, conf)
  112. if err != nil {
  113. logger.Debug("Failed to unmarshal inbound:", err)
  114. return err
  115. }
  116. config, err := conf.Build()
  117. if err != nil {
  118. logger.Debug("Failed to build inbound Detur:", err)
  119. return err
  120. }
  121. inboundConfig := command.AddInboundRequest{Inbound: config}
  122. _, err = client.AddInbound(context.Background(), &inboundConfig)
  123. return err
  124. }
  125. // DelInbound removes an inbound configuration from the Xray core by tag.
  126. func (x *XrayAPI) DelInbound(tag string) error {
  127. client := *x.HandlerServiceClient
  128. _, err := client.RemoveInbound(context.Background(), &command.RemoveInboundRequest{
  129. Tag: tag,
  130. })
  131. return err
  132. }
  133. // AddOutbound adds a new outbound configuration to the Xray core via gRPC.
  134. func (x *XrayAPI) AddOutbound(outbound []byte) error {
  135. if x.HandlerServiceClient == nil {
  136. return common.NewError("xray HandlerServiceClient is not initialized")
  137. }
  138. client := *x.HandlerServiceClient
  139. conf := new(conf.OutboundDetourConfig)
  140. if err := json.Unmarshal(outbound, conf); err != nil {
  141. logger.Debug("Failed to unmarshal outbound:", err)
  142. return err
  143. }
  144. config, err := conf.Build()
  145. if err != nil {
  146. logger.Debug("Failed to build outbound detour:", err)
  147. return err
  148. }
  149. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  150. defer cancel()
  151. _, err = client.AddOutbound(ctx, &command.AddOutboundRequest{Outbound: config})
  152. return err
  153. }
  154. // DelOutbound removes an outbound configuration from the Xray core by tag.
  155. func (x *XrayAPI) DelOutbound(tag string) error {
  156. if x.HandlerServiceClient == nil {
  157. return common.NewError("xray HandlerServiceClient is not initialized")
  158. }
  159. client := *x.HandlerServiceClient
  160. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  161. defer cancel()
  162. _, err := client.RemoveOutbound(ctx, &command.RemoveOutboundRequest{Tag: tag})
  163. return err
  164. }
  165. // ApplyRoutingConfig replaces the routing rules and balancers of the running
  166. // Xray core with the given routing section (the JSON value of the top-level
  167. // "routing" key) via the RoutingService gRPC API. Note that this cannot change
  168. // routing.domainStrategy/domainMatcher — those are fixed at process start.
  169. func (x *XrayAPI) ApplyRoutingConfig(routing []byte) error {
  170. if x.RoutingServiceClient == nil {
  171. return common.NewError("xray RoutingServiceClient is not initialized")
  172. }
  173. // Rules referencing geoip:/geosite: need the dat files; point xray-core's
  174. // in-process loader at the panel's bin folder where they live.
  175. ensureXrayAssetLocation()
  176. routerConf := new(conf.RouterConfig)
  177. if err := json.Unmarshal(routing, routerConf); err != nil {
  178. logger.Debug("Failed to unmarshal routing config:", err)
  179. return err
  180. }
  181. config, err := routerConf.Build()
  182. if err != nil {
  183. logger.Debug("Failed to build routing config:", err)
  184. return err
  185. }
  186. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  187. defer cancel()
  188. _, err = (*x.RoutingServiceClient).AddRule(ctx, &routerService.AddRuleRequest{
  189. ShouldAppend: false,
  190. Config: serial.ToTypedMessage(config),
  191. })
  192. return err
  193. }
  194. // BalancerInfo is the live state of one balancer inside the running core.
  195. type BalancerInfo struct {
  196. Tag string `json:"tag"`
  197. // Override is the outbound tag an admin forced via the API; empty when
  198. // the strategy is in control.
  199. Override string `json:"override"`
  200. // Selected are the outbound tags the strategy currently prefers, best
  201. // first (xray's "principle target" list).
  202. Selected []string `json:"selected"`
  203. }
  204. // GetBalancerInfo queries the running core for a balancer's current override
  205. // and the targets its strategy would pick right now.
  206. func (x *XrayAPI) GetBalancerInfo(tag string) (*BalancerInfo, error) {
  207. if x.RoutingServiceClient == nil {
  208. return nil, common.NewError("xray RoutingServiceClient is not initialized")
  209. }
  210. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  211. defer cancel()
  212. resp, err := (*x.RoutingServiceClient).GetBalancerInfo(ctx, &routerService.GetBalancerInfoRequest{Tag: tag})
  213. if err != nil {
  214. return nil, err
  215. }
  216. info := &BalancerInfo{Tag: tag}
  217. if balancer := resp.GetBalancer(); balancer != nil {
  218. if balancer.Override != nil {
  219. info.Override = balancer.Override.Target
  220. }
  221. if balancer.PrincipleTarget != nil {
  222. info.Selected = balancer.PrincipleTarget.Tag
  223. }
  224. }
  225. return info, nil
  226. }
  227. // SetBalancerTarget forces a balancer to always pick the given outbound tag.
  228. // An empty target clears the override and hands control back to the strategy.
  229. func (x *XrayAPI) SetBalancerTarget(tag, target string) error {
  230. if x.RoutingServiceClient == nil {
  231. return common.NewError("xray RoutingServiceClient is not initialized")
  232. }
  233. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  234. defer cancel()
  235. _, err := (*x.RoutingServiceClient).OverrideBalancerTarget(ctx, &routerService.OverrideBalancerTargetRequest{
  236. BalancerTag: tag,
  237. Target: target,
  238. })
  239. return err
  240. }
  241. // RouteTestRequest describes a synthetic connection to ask the running core
  242. // which outbound its router would pick for it.
  243. type RouteTestRequest struct {
  244. InboundTag string // optional: simulate arrival on this inbound
  245. Domain string // target domain (sniffed/SOCKS-style destination)
  246. IP string // target IP, used when Domain is empty or alongside it
  247. Port int
  248. Network string // "tcp" (default) or "udp"
  249. Protocol string // optional sniffed protocol: http, tls, bittorrent, ...
  250. Email string // optional user attribution for user-based rules
  251. }
  252. // RouteTestResult is the routing decision the core reported.
  253. type RouteTestResult struct {
  254. // Matched is false when no routing rule matched — traffic would use the
  255. // default (first) outbound and OutboundTag is empty.
  256. Matched bool `json:"matched"`
  257. OutboundTag string `json:"outboundTag"`
  258. // GroupTags lists the balancer chain the decision went through, when any.
  259. GroupTags []string `json:"groupTags,omitempty"`
  260. }
  261. // TestRoute asks the running core's router which outbound it would pick for
  262. // the described connection, without sending any traffic.
  263. func (x *XrayAPI) TestRoute(req RouteTestRequest) (*RouteTestResult, error) {
  264. if x.RoutingServiceClient == nil {
  265. return nil, common.NewError("xray RoutingServiceClient is not initialized")
  266. }
  267. network := xnet.Network_TCP
  268. if strings.EqualFold(req.Network, "udp") {
  269. network = xnet.Network_UDP
  270. }
  271. rc := &routerService.RoutingContext{
  272. InboundTag: req.InboundTag,
  273. Network: network,
  274. TargetDomain: req.Domain,
  275. TargetPort: uint32(req.Port),
  276. Protocol: req.Protocol,
  277. User: req.Email,
  278. }
  279. if req.IP != "" {
  280. parsed := net.ParseIP(req.IP)
  281. if parsed == nil {
  282. return nil, common.NewErrorf("invalid IP address: %s", req.IP)
  283. }
  284. if v4 := parsed.To4(); v4 != nil {
  285. rc.TargetIPs = [][]byte{v4}
  286. } else {
  287. rc.TargetIPs = [][]byte{parsed.To16()}
  288. }
  289. }
  290. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  291. defer cancel()
  292. resp, err := (*x.RoutingServiceClient).TestRoute(ctx, &routerService.TestRouteRequest{
  293. RoutingContext: rc,
  294. PublishResult: false,
  295. })
  296. if err != nil {
  297. // The router reports "no rule matched" as an error; for the caller
  298. // that simply means the default outbound takes the traffic.
  299. if strings.Contains(strings.ToLower(err.Error()), "not enough information") {
  300. return &RouteTestResult{Matched: false}, nil
  301. }
  302. return nil, err
  303. }
  304. return &RouteTestResult{
  305. Matched: true,
  306. OutboundTag: resp.GetOutboundTag(),
  307. GroupTags: resp.GetOutboundGroupTags(),
  308. }, nil
  309. }
  310. // IsMissingHandlerErr reports whether err is xray's response to removing a
  311. // handler (inbound/outbound) that does not exist — e.g. it was already
  312. // removed through the runtime API while the panel's config snapshot was
  313. // stale. Safe to treat as success for removal operations.
  314. func IsMissingHandlerErr(err error) bool {
  315. if err == nil {
  316. return false
  317. }
  318. msg := strings.ToLower(err.Error())
  319. return strings.Contains(msg, "not found") ||
  320. strings.Contains(msg, "not enough information")
  321. }
  322. // IsExistingTagErr reports whether err is xray's response to adding a handler
  323. // whose tag is already taken by a running handler.
  324. func IsExistingTagErr(err error) bool {
  325. if err == nil {
  326. return false
  327. }
  328. return strings.Contains(strings.ToLower(err.Error()), "existing tag")
  329. }
  330. // ensureXrayAssetLocation makes geoip.dat/geosite.dat resolvable when xray-core
  331. // config builders run inside the panel process. The xray binary resolves assets
  332. // relative to its own executable, but the panel binary lives one level above
  333. // the bin folder, so an explicit location is required.
  334. func ensureXrayAssetLocation() {
  335. if os.Getenv("XRAY_LOCATION_ASSET") != "" || os.Getenv("xray.location.asset") != "" {
  336. return
  337. }
  338. if abs, err := filepath.Abs(config.GetBinFolderPath()); err == nil {
  339. os.Setenv("XRAY_LOCATION_ASSET", abs)
  340. }
  341. }
  342. // AddUser adds a user to an inbound in the Xray core using the specified protocol and user data.
  343. func (x *XrayAPI) AddUser(Protocol string, inboundTag string, user map[string]any) error {
  344. userEmail, err := getRequiredUserString(user, "email")
  345. if err != nil {
  346. return err
  347. }
  348. var account *serial.TypedMessage
  349. switch Protocol {
  350. case "vmess":
  351. userID, err := getRequiredUserString(user, "id")
  352. if err != nil {
  353. return err
  354. }
  355. account = serial.ToTypedMessage(&vmess.Account{
  356. Id: userID,
  357. })
  358. case "vless":
  359. userID, err := getRequiredUserString(user, "id")
  360. if err != nil {
  361. return err
  362. }
  363. userFlow, err := getOptionalUserString(user, "flow")
  364. if err != nil {
  365. return err
  366. }
  367. vlessAccount := &vless.Account{
  368. Id: userID,
  369. Flow: userFlow,
  370. }
  371. // Add testseed if provided
  372. if testseedVal, ok := user["testseed"]; ok {
  373. if testseedArr, ok := testseedVal.([]any); ok && len(testseedArr) >= 4 {
  374. testseed := make([]uint32, len(testseedArr))
  375. for i, v := range testseedArr {
  376. if num, ok := v.(float64); ok {
  377. testseed[i] = uint32(num)
  378. }
  379. }
  380. vlessAccount.Testseed = testseed
  381. } else if testseedArr, ok := testseedVal.([]uint32); ok && len(testseedArr) >= 4 {
  382. vlessAccount.Testseed = testseedArr
  383. }
  384. }
  385. // Add testpre if provided (for outbound, but can be in user for compatibility)
  386. if testpreVal, ok := user["testpre"]; ok {
  387. if testpre, ok := testpreVal.(float64); ok && testpre > 0 {
  388. vlessAccount.Testpre = uint32(testpre)
  389. } else if testpre, ok := testpreVal.(uint32); ok && testpre > 0 {
  390. vlessAccount.Testpre = testpre
  391. }
  392. }
  393. account = serial.ToTypedMessage(vlessAccount)
  394. case "trojan":
  395. password, err := getRequiredUserString(user, "password")
  396. if err != nil {
  397. return err
  398. }
  399. account = serial.ToTypedMessage(&trojan.Account{
  400. Password: password,
  401. })
  402. case "shadowsocks":
  403. cipher, err := getOptionalUserString(user, "cipher")
  404. if err != nil {
  405. return err
  406. }
  407. password, err := getRequiredUserString(user, "password")
  408. if err != nil {
  409. return err
  410. }
  411. var ssCipherType shadowsocks.CipherType
  412. switch cipher {
  413. case "aes-256-gcm":
  414. ssCipherType = shadowsocks.CipherType_AES_256_GCM
  415. case "chacha20-poly1305", "chacha20-ietf-poly1305":
  416. ssCipherType = shadowsocks.CipherType_CHACHA20_POLY1305
  417. case "xchacha20-poly1305", "xchacha20-ietf-poly1305":
  418. ssCipherType = shadowsocks.CipherType_XCHACHA20_POLY1305
  419. default:
  420. ssCipherType = shadowsocks.CipherType_NONE
  421. }
  422. if ssCipherType != shadowsocks.CipherType_NONE {
  423. account = serial.ToTypedMessage(&shadowsocks.Account{
  424. Password: password,
  425. CipherType: ssCipherType,
  426. })
  427. } else {
  428. account = serial.ToTypedMessage(&shadowsocks_2022.ServerConfig{
  429. Key: password,
  430. Email: userEmail,
  431. })
  432. }
  433. case "hysteria":
  434. auth, err := getRequiredUserString(user, "auth")
  435. if err != nil {
  436. return err
  437. }
  438. account = serial.ToTypedMessage(&hysteriaAccount.Account{
  439. Auth: auth,
  440. })
  441. default:
  442. return nil
  443. }
  444. client := *x.HandlerServiceClient
  445. _, err = client.AlterInbound(context.Background(), &command.AlterInboundRequest{
  446. Tag: inboundTag,
  447. Operation: serial.ToTypedMessage(&command.AddUserOperation{
  448. User: &protocol.User{
  449. Email: userEmail,
  450. Account: account,
  451. },
  452. }),
  453. })
  454. return err
  455. }
  456. // RemoveUser removes a user from an inbound in the Xray core by email.
  457. func (x *XrayAPI) RemoveUser(inboundTag, email string) error {
  458. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  459. defer cancel()
  460. op := &command.RemoveUserOperation{Email: email}
  461. req := &command.AlterInboundRequest{
  462. Tag: inboundTag,
  463. Operation: serial.ToTypedMessage(op),
  464. }
  465. _, err := (*x.HandlerServiceClient).AlterInbound(ctx, req)
  466. if err != nil {
  467. return fmt.Errorf("failed to remove user: %w", err)
  468. }
  469. return nil
  470. }
  471. // GetTraffic queries traffic statistics from the Xray core, optionally resetting counters.
  472. func (x *XrayAPI) GetTraffic() ([]*Traffic, []*ClientTraffic, error) {
  473. if x.grpcClient == nil {
  474. return nil, nil, common.NewError("xray api is not initialized")
  475. }
  476. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  477. defer cancel()
  478. if x.StatsServiceClient == nil {
  479. return nil, nil, common.NewError("xray StatusServiceClient is not initialized")
  480. }
  481. resp, err := (*x.StatsServiceClient).QueryStats(ctx, &statsService.QueryStatsRequest{Reset_: false})
  482. if err != nil {
  483. logger.Debug("Failed to query Xray stats:", err)
  484. return nil, nil, err
  485. }
  486. tagTrafficMap := make(map[string]*Traffic)
  487. emailTrafficMap := make(map[string]*ClientTraffic)
  488. for _, stat := range resp.GetStat() {
  489. lastValue, ok := x.StatsLastValues[stat.Name]
  490. x.StatsLastValues[stat.Name] = stat.Value
  491. if !ok || stat.Value < lastValue {
  492. // skip first time of seen stat
  493. continue
  494. }
  495. value := stat.Value - lastValue
  496. if matches := trafficRegex.FindStringSubmatch(stat.Name); len(matches) == 4 {
  497. processTraffic(matches, value, tagTrafficMap)
  498. } else if matches := clientTrafficRegex.FindStringSubmatch(stat.Name); len(matches) == 3 {
  499. processClientTraffic(matches, value, emailTrafficMap)
  500. }
  501. }
  502. return mapToSlice(tagTrafficMap), mapToSlice(emailTrafficMap), nil
  503. }
  504. // OnlineIP is one source address of a live connection, with the unix time (seconds)
  505. // the core last dispatched a link from it.
  506. type OnlineIP struct {
  507. IP string `json:"ip"`
  508. LastSeen int64 `json:"lastSeen"`
  509. }
  510. // OnlineUser is a client email with at least one live connection and the source
  511. // IPs of those connections, as tracked by Xray's statsUserOnline policy.
  512. type OnlineUser struct {
  513. Email string `json:"email"`
  514. IPs []OnlineIP `json:"ips"`
  515. }
  516. // GetOnlineUsers returns every user with at least one live connection plus their
  517. // source IPs, via StatsService.GetUsersStats (one RPC covers all users). Requires
  518. // statsUserOnline enabled in the policy levels; older cores return Unimplemented.
  519. func (x *XrayAPI) GetOnlineUsers() ([]OnlineUser, error) {
  520. if x.grpcClient == nil {
  521. return nil, common.NewError("xray api is not initialized")
  522. }
  523. if x.StatsServiceClient == nil {
  524. return nil, common.NewError("xray StatsServiceClient is not initialized")
  525. }
  526. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  527. defer cancel()
  528. resp, err := (*x.StatsServiceClient).GetUsersStats(ctx, &statsService.GetUsersStatsRequest{})
  529. if err != nil {
  530. return nil, err
  531. }
  532. users := make([]OnlineUser, 0, len(resp.GetUsers()))
  533. for _, u := range resp.GetUsers() {
  534. if u == nil || u.GetEmail() == "" {
  535. continue
  536. }
  537. ips := make([]OnlineIP, 0, len(u.GetIps()))
  538. for _, entry := range u.GetIps() {
  539. if entry == nil || entry.GetIp() == "" {
  540. continue
  541. }
  542. ips = append(ips, OnlineIP{IP: entry.GetIp(), LastSeen: entry.GetLastSeen()})
  543. }
  544. users = append(users, OnlineUser{Email: u.GetEmail(), IPs: ips})
  545. }
  546. return users, nil
  547. }
  548. // IsUnimplementedErr reports whether err is the running core saying it lacks an
  549. // RPC (an older Xray binary without the online-stats API).
  550. func IsUnimplementedErr(err error) bool {
  551. return status.Code(err) == codes.Unimplemented
  552. }
  553. // processTraffic aggregates a traffic stat into trafficMap using regex matches and value.
  554. func processTraffic(matches []string, value int64, trafficMap map[string]*Traffic) {
  555. isInbound := matches[1] == "inbound"
  556. tag := matches[2]
  557. isDown := matches[3] == "downlink"
  558. if tag == "api" {
  559. return
  560. }
  561. traffic, ok := trafficMap[tag]
  562. if !ok {
  563. traffic = &Traffic{
  564. IsInbound: isInbound,
  565. IsOutbound: !isInbound,
  566. Tag: tag,
  567. }
  568. trafficMap[tag] = traffic
  569. }
  570. if isDown {
  571. traffic.Down = value
  572. } else {
  573. traffic.Up = value
  574. }
  575. }
  576. // processClientTraffic updates clientTrafficMap with upload/download values for a client email.
  577. func processClientTraffic(matches []string, value int64, clientTrafficMap map[string]*ClientTraffic) {
  578. email := matches[1]
  579. isDown := matches[2] == "downlink"
  580. traffic, ok := clientTrafficMap[email]
  581. if !ok {
  582. traffic = &ClientTraffic{Email: email}
  583. clientTrafficMap[email] = traffic
  584. }
  585. if isDown {
  586. traffic.Down = value
  587. } else {
  588. traffic.Up = value
  589. }
  590. }
  591. // mapToSlice converts a map of pointers to a slice of pointers.
  592. func mapToSlice[T any](m map[string]*T) []*T {
  593. result := make([]*T, 0, len(m))
  594. for _, v := range m {
  595. result = append(result, v)
  596. }
  597. return result
  598. }