api.go 24 KB

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