api.go 25 KB

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