1
0

api.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  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. // IsUserExistsErr reports whether err is xray's response to adding a user whose
  347. // email is already registered on the inbound.
  348. func IsUserExistsErr(err error) bool {
  349. if err == nil {
  350. return false
  351. }
  352. return strings.Contains(strings.ToLower(err.Error()), "already exists")
  353. }
  354. // ensureXrayAssetLocation makes geoip.dat/geosite.dat resolvable when xray-core
  355. // config builders run inside the panel process. The xray binary resolves assets
  356. // relative to its own executable, but the panel binary lives one level above
  357. // the bin folder, so an explicit location is required.
  358. func ensureXrayAssetLocation() {
  359. if os.Getenv("XRAY_LOCATION_ASSET") != "" || os.Getenv("xray.location.asset") != "" {
  360. return
  361. }
  362. if abs, err := filepath.Abs(config.GetBinFolderPath()); err == nil {
  363. os.Setenv("XRAY_LOCATION_ASSET", abs)
  364. }
  365. }
  366. // collectStringSlice normalizes a JSON-decoded value into a slice of non-empty
  367. // strings, accepting both []string (typed maps) and []any (json.Unmarshal output).
  368. func collectStringSlice(value any) []string {
  369. switch v := value.(type) {
  370. case []string:
  371. out := make([]string, 0, len(v))
  372. for _, s := range v {
  373. if s != "" {
  374. out = append(out, s)
  375. }
  376. }
  377. return out
  378. case []any:
  379. out := make([]string, 0, len(v))
  380. for _, e := range v {
  381. if s, ok := e.(string); ok && s != "" {
  382. out = append(out, s)
  383. }
  384. }
  385. return out
  386. default:
  387. return nil
  388. }
  389. }
  390. // buildUserAccount constructs the typed xray account for a user of the given
  391. // protocol. It returns (nil, nil) for protocols that cannot be altered live so
  392. // callers skip the AlterInbound call. WireGuard keys must be converted to the
  393. // hex form xray's wireguard proxy expects (its ParseKey uses hex.DecodeString),
  394. // unlike the file-config path which accepts base64 and converts internally.
  395. func buildUserAccount(protocolName string, user map[string]any) (*serial.TypedMessage, error) {
  396. switch protocolName {
  397. case "vmess":
  398. userID, err := getRequiredUserString(user, "id")
  399. if err != nil {
  400. return nil, err
  401. }
  402. return serial.ToTypedMessage(&vmess.Account{
  403. Id: userID,
  404. }), nil
  405. case "vless":
  406. userID, err := getRequiredUserString(user, "id")
  407. if err != nil {
  408. return nil, err
  409. }
  410. userFlow, err := getOptionalUserString(user, "flow")
  411. if err != nil {
  412. return nil, err
  413. }
  414. vlessAccount := &vless.Account{
  415. Id: userID,
  416. Flow: userFlow,
  417. }
  418. if testseedVal, ok := user["testseed"]; ok {
  419. if testseedArr, ok := testseedVal.([]any); ok && len(testseedArr) >= 4 {
  420. testseed := make([]uint32, len(testseedArr))
  421. for i, v := range testseedArr {
  422. if num, ok := v.(float64); ok {
  423. testseed[i] = uint32(num)
  424. }
  425. }
  426. vlessAccount.Testseed = testseed
  427. } else if testseedArr, ok := testseedVal.([]uint32); ok && len(testseedArr) >= 4 {
  428. vlessAccount.Testseed = testseedArr
  429. }
  430. }
  431. if testpreVal, ok := user["testpre"]; ok {
  432. if testpre, ok := testpreVal.(float64); ok && testpre > 0 {
  433. vlessAccount.Testpre = uint32(testpre)
  434. } else if testpre, ok := testpreVal.(uint32); ok && testpre > 0 {
  435. vlessAccount.Testpre = testpre
  436. }
  437. }
  438. return serial.ToTypedMessage(vlessAccount), nil
  439. case "trojan":
  440. password, err := getRequiredUserString(user, "password")
  441. if err != nil {
  442. return nil, err
  443. }
  444. return serial.ToTypedMessage(&trojan.Account{
  445. Password: password,
  446. }), nil
  447. case "shadowsocks":
  448. cipher, err := getOptionalUserString(user, "cipher")
  449. if err != nil {
  450. return nil, err
  451. }
  452. password, err := getRequiredUserString(user, "password")
  453. if err != nil {
  454. return nil, err
  455. }
  456. var ssCipherType shadowsocks.CipherType
  457. switch cipher {
  458. case "aes-256-gcm":
  459. ssCipherType = shadowsocks.CipherType_AES_256_GCM
  460. case "chacha20-poly1305", "chacha20-ietf-poly1305":
  461. ssCipherType = shadowsocks.CipherType_CHACHA20_POLY1305
  462. case "xchacha20-poly1305", "xchacha20-ietf-poly1305":
  463. ssCipherType = shadowsocks.CipherType_XCHACHA20_POLY1305
  464. default:
  465. ssCipherType = shadowsocks.CipherType_NONE
  466. }
  467. if ssCipherType != shadowsocks.CipherType_NONE {
  468. return serial.ToTypedMessage(&shadowsocks.Account{
  469. Password: password,
  470. CipherType: ssCipherType,
  471. }), nil
  472. }
  473. return serial.ToTypedMessage(&shadowsocks_2022.Account{
  474. Key: password,
  475. }), nil
  476. case "hysteria":
  477. auth, err := getRequiredUserString(user, "auth")
  478. if err != nil {
  479. return nil, err
  480. }
  481. return serial.ToTypedMessage(&hysteriaAccount.Account{
  482. Auth: auth,
  483. }), nil
  484. case "wireguard":
  485. pubB64, err := getRequiredUserString(user, "publicKey")
  486. if err != nil {
  487. return nil, err
  488. }
  489. pubHex, err := wgutil.KeyToHex(pubB64)
  490. if err != nil {
  491. return nil, fmt.Errorf("wireguard publicKey: %w", err)
  492. }
  493. pskB64, err := getOptionalUserString(user, "preSharedKey")
  494. if err != nil {
  495. return nil, err
  496. }
  497. pskHex, err := wgutil.KeyToHex(pskB64)
  498. if err != nil {
  499. return nil, fmt.Errorf("wireguard preSharedKey: %w", err)
  500. }
  501. allowed := collectStringSlice(user["allowedIPs"])
  502. if len(allowed) == 0 {
  503. return nil, common.NewError("wireguard: allowedIPs required")
  504. }
  505. keepAlive, err := getOptionalUserString(user, "keepAlive")
  506. if err != nil {
  507. return nil, err
  508. }
  509. return serial.ToTypedMessage(&wireguard.PeerConfig{
  510. PublicKey: pubHex,
  511. PreSharedKey: pskHex,
  512. AllowedIps: allowed,
  513. KeepAlive: keepAlive,
  514. }), nil
  515. default:
  516. return nil, nil
  517. }
  518. }
  519. // AddUser adds a user to an inbound in the Xray core using the specified protocol and user data.
  520. func (x *XrayAPI) AddUser(Protocol string, inboundTag string, user map[string]any) error {
  521. userEmail, err := getRequiredUserString(user, "email")
  522. if err != nil {
  523. return err
  524. }
  525. account, err := buildUserAccount(Protocol, user)
  526. if err != nil {
  527. return err
  528. }
  529. if account == nil {
  530. return nil
  531. }
  532. if x.HandlerServiceClient == nil {
  533. return common.NewError("xray HandlerServiceClient is not initialized")
  534. }
  535. client := *x.HandlerServiceClient
  536. ctx, cancel := context.WithTimeout(context.Background(), handlerRPCTimeout)
  537. defer cancel()
  538. _, err = client.AlterInbound(ctx, &command.AlterInboundRequest{
  539. Tag: inboundTag,
  540. Operation: serial.ToTypedMessage(&command.AddUserOperation{
  541. User: &protocol.User{
  542. Email: userEmail,
  543. Account: account,
  544. },
  545. }),
  546. })
  547. return err
  548. }
  549. // RemoveUser removes a user from an inbound in the Xray core by email.
  550. func (x *XrayAPI) RemoveUser(inboundTag, email string) error {
  551. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  552. defer cancel()
  553. op := &command.RemoveUserOperation{Email: email}
  554. req := &command.AlterInboundRequest{
  555. Tag: inboundTag,
  556. Operation: serial.ToTypedMessage(op),
  557. }
  558. _, err := (*x.HandlerServiceClient).AlterInbound(ctx, req)
  559. if err != nil {
  560. return fmt.Errorf("failed to remove user: %w", err)
  561. }
  562. return nil
  563. }
  564. // GetTraffic queries traffic statistics from the Xray core, optionally resetting counters.
  565. func (x *XrayAPI) GetTraffic() ([]*Traffic, []*ClientTraffic, error) {
  566. if x.grpcClient == nil {
  567. return nil, nil, common.NewError("xray api is not initialized")
  568. }
  569. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  570. defer cancel()
  571. if x.StatsServiceClient == nil {
  572. return nil, nil, common.NewError("xray StatusServiceClient is not initialized")
  573. }
  574. resp, err := (*x.StatsServiceClient).QueryStats(ctx, &statsService.QueryStatsRequest{Reset_: false})
  575. if err != nil {
  576. logger.Debug("Failed to query Xray stats:", err)
  577. return nil, nil, err
  578. }
  579. tagTrafficMap := make(map[string]*Traffic)
  580. emailTrafficMap := make(map[string]*ClientTraffic)
  581. for _, stat := range resp.GetStat() {
  582. lastValue, ok := x.StatsLastValues[stat.Name]
  583. x.StatsLastValues[stat.Name] = stat.Value
  584. if !ok || stat.Value < lastValue {
  585. // skip first time of seen stat
  586. continue
  587. }
  588. value := stat.Value - lastValue
  589. if matches := trafficRegex.FindStringSubmatch(stat.Name); len(matches) == 4 {
  590. processTraffic(matches, value, tagTrafficMap)
  591. } else if matches := clientTrafficRegex.FindStringSubmatch(stat.Name); len(matches) == 3 {
  592. processClientTraffic(matches, value, emailTrafficMap)
  593. }
  594. }
  595. // Drop delta baselines for stats that no longer exist (deleted inbounds or
  596. // clients), which otherwise linger until the next Xray restart. Only rebuild
  597. // when the map has drifted past 2x the live set, so the steady-state hot path
  598. // stays allocation-free.
  599. if n := len(resp.GetStat()); n > 0 && len(x.StatsLastValues) > 2*n {
  600. pruned := make(map[string]int64, n)
  601. for _, stat := range resp.GetStat() {
  602. pruned[stat.Name] = x.StatsLastValues[stat.Name]
  603. }
  604. x.StatsLastValues = pruned
  605. }
  606. return mapToSlice(tagTrafficMap), mapToSlice(emailTrafficMap), nil
  607. }
  608. // OnlineIP is one source address of a live connection, with the unix time (seconds)
  609. // the core last dispatched a link from it.
  610. type OnlineIP struct {
  611. IP string `json:"ip"`
  612. LastSeen int64 `json:"lastSeen"`
  613. }
  614. // OnlineUser is a client email with at least one live connection and the source
  615. // IPs of those connections, as tracked by Xray's statsUserOnline policy.
  616. type OnlineUser struct {
  617. Email string `json:"email"`
  618. IPs []OnlineIP `json:"ips"`
  619. }
  620. // GetOnlineUsers returns every user with at least one live connection plus their
  621. // source IPs, via StatsService.GetUsersStats (one RPC covers all users). Requires
  622. // statsUserOnline enabled in the policy levels; older cores return Unimplemented.
  623. func (x *XrayAPI) GetOnlineUsers() ([]OnlineUser, error) {
  624. if x.grpcClient == nil {
  625. return nil, common.NewError("xray api is not initialized")
  626. }
  627. if x.StatsServiceClient == nil {
  628. return nil, common.NewError("xray StatsServiceClient is not initialized")
  629. }
  630. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  631. defer cancel()
  632. resp, err := (*x.StatsServiceClient).GetUsersStats(ctx, &statsService.GetUsersStatsRequest{})
  633. if err != nil {
  634. return nil, err
  635. }
  636. users := make([]OnlineUser, 0, len(resp.GetUsers()))
  637. for _, u := range resp.GetUsers() {
  638. if u == nil || u.GetEmail() == "" {
  639. continue
  640. }
  641. ips := make([]OnlineIP, 0, len(u.GetIps()))
  642. for _, entry := range u.GetIps() {
  643. if entry == nil || entry.GetIp() == "" {
  644. continue
  645. }
  646. ips = append(ips, OnlineIP{IP: entry.GetIp(), LastSeen: entry.GetLastSeen()})
  647. }
  648. users = append(users, OnlineUser{Email: u.GetEmail(), IPs: ips})
  649. }
  650. return users, nil
  651. }
  652. // IsUnimplementedErr reports whether err is the running core saying it lacks an
  653. // RPC (an older Xray binary without the online-stats API).
  654. func IsUnimplementedErr(err error) bool {
  655. return status.Code(err) == codes.Unimplemented
  656. }
  657. // processTraffic aggregates a traffic stat into trafficMap using regex matches and value.
  658. func processTraffic(matches []string, value int64, trafficMap map[string]*Traffic) {
  659. isInbound := matches[1] == "inbound"
  660. tag := matches[2]
  661. isDown := matches[3] == "downlink"
  662. if tag == "api" {
  663. return
  664. }
  665. traffic, ok := trafficMap[tag]
  666. if !ok {
  667. traffic = &Traffic{
  668. IsInbound: isInbound,
  669. IsOutbound: !isInbound,
  670. Tag: tag,
  671. }
  672. trafficMap[tag] = traffic
  673. }
  674. if isDown {
  675. traffic.Down = value
  676. } else {
  677. traffic.Up = value
  678. }
  679. }
  680. // processClientTraffic updates clientTrafficMap with upload/download values for a client email.
  681. func processClientTraffic(matches []string, value int64, clientTrafficMap map[string]*ClientTraffic) {
  682. email := matches[1]
  683. isDown := matches[2] == "downlink"
  684. traffic, ok := clientTrafficMap[email]
  685. if !ok {
  686. traffic = &ClientTraffic{Email: email}
  687. clientTrafficMap[email] = traffic
  688. }
  689. if isDown {
  690. traffic.Down = value
  691. } else {
  692. traffic.Up = value
  693. }
  694. }
  695. // mapToSlice converts a map of pointers to a slice of pointers.
  696. func mapToSlice[T any](m map[string]*T) []*T {
  697. result := make([]*T, 0, len(m))
  698. for _, v := range m {
  699. result = append(result, v)
  700. }
  701. return result
  702. }