api.go 21 KB

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