api.go 21 KB

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