api.go 25 KB

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