api.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  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. if req.Port < 0 || req.Port > math.MaxUint16 {
  298. return nil, common.NewErrorf("invalid port: %d", req.Port)
  299. }
  300. network := xnet.Network_TCP
  301. if strings.EqualFold(req.Network, "udp") {
  302. network = xnet.Network_UDP
  303. }
  304. rc := &routerService.RoutingContext{
  305. InboundTag: req.InboundTag,
  306. Network: network,
  307. TargetDomain: req.Domain,
  308. TargetPort: uint32(req.Port),
  309. Protocol: req.Protocol,
  310. User: req.Email,
  311. }
  312. if req.IP != "" {
  313. parsed := net.ParseIP(req.IP)
  314. if parsed == nil {
  315. return nil, common.NewErrorf("invalid IP address: %s", req.IP)
  316. }
  317. if v4 := parsed.To4(); v4 != nil {
  318. rc.TargetIPs = [][]byte{v4}
  319. } else {
  320. rc.TargetIPs = [][]byte{parsed.To16()}
  321. }
  322. }
  323. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  324. defer cancel()
  325. resp, err := (*x.RoutingServiceClient).TestRoute(ctx, &routerService.TestRouteRequest{
  326. RoutingContext: rc,
  327. PublishResult: false,
  328. })
  329. if err != nil {
  330. // The router reports "no rule matched" as an error; for the caller
  331. // that simply means the default outbound takes the traffic.
  332. if strings.Contains(strings.ToLower(err.Error()), "not enough information") {
  333. return &RouteTestResult{Matched: false}, nil
  334. }
  335. return nil, err
  336. }
  337. return &RouteTestResult{
  338. Matched: true,
  339. OutboundTag: resp.GetOutboundTag(),
  340. GroupTags: resp.GetOutboundGroupTags(),
  341. }, nil
  342. }
  343. // IsMissingHandlerErr reports whether err is xray's response to removing a
  344. // handler (inbound/outbound) that does not exist — e.g. it was already
  345. // removed through the runtime API while the panel's config snapshot was
  346. // stale. Safe to treat as success for removal operations.
  347. func IsMissingHandlerErr(err error) bool {
  348. if err == nil {
  349. return false
  350. }
  351. msg := strings.ToLower(err.Error())
  352. return strings.Contains(msg, "not found") ||
  353. strings.Contains(msg, "not enough information")
  354. }
  355. // IsExistingTagErr reports whether err is xray's response to adding a handler
  356. // whose tag is already taken by a running handler.
  357. func IsExistingTagErr(err error) bool {
  358. if err == nil {
  359. return false
  360. }
  361. return strings.Contains(strings.ToLower(err.Error()), "existing tag")
  362. }
  363. // IsUserExistsErr reports whether err is xray's response to adding a user whose
  364. // email is already registered on the inbound.
  365. func IsUserExistsErr(err error) bool {
  366. if err == nil {
  367. return false
  368. }
  369. return strings.Contains(strings.ToLower(err.Error()), "already exists")
  370. }
  371. // ensureXrayAssetLocation makes geoip.dat/geosite.dat resolvable when xray-core
  372. // config builders run inside the panel process. The xray binary resolves assets
  373. // relative to its own executable, but the panel binary lives one level above
  374. // the bin folder, so an explicit location is required.
  375. func ensureXrayAssetLocation() {
  376. if os.Getenv("XRAY_LOCATION_ASSET") != "" || os.Getenv("xray.location.asset") != "" {
  377. return
  378. }
  379. if abs, err := filepath.Abs(config.GetBinFolderPath()); err == nil {
  380. os.Setenv("XRAY_LOCATION_ASSET", abs)
  381. }
  382. }
  383. // collectStringSlice normalizes a JSON-decoded value into a slice of non-empty
  384. // strings, accepting both []string (typed maps) and []any (json.Unmarshal output).
  385. func collectStringSlice(value any) []string {
  386. switch v := value.(type) {
  387. case []string:
  388. out := make([]string, 0, len(v))
  389. for _, s := range v {
  390. if s != "" {
  391. out = append(out, s)
  392. }
  393. }
  394. return out
  395. case []any:
  396. out := make([]string, 0, len(v))
  397. for _, e := range v {
  398. if s, ok := e.(string); ok && s != "" {
  399. out = append(out, s)
  400. }
  401. }
  402. return out
  403. default:
  404. return nil
  405. }
  406. }
  407. // legacyShadowsocksAccountType is the type URL serial.ToTypedMessage stamps on
  408. // a pre-2022 shadowsocks account, which identifies the one inbound whose user
  409. // list tolerates duplicate emails.
  410. const legacyShadowsocksAccountType = "xray.proxy.shadowsocks.Account"
  411. // shadowsocks2022Ciphers are the methods that select xray's shadowsocks-2022
  412. // inbound (sing's shadowaead_2022 list). They take a different account type
  413. // than the legacy AEAD ciphers, and the running inbound casts the account it
  414. // receives without checking, so a wrong guess takes the whole core down.
  415. var shadowsocks2022Ciphers = map[string]struct{}{
  416. "2022-blake3-aes-128-gcm": {},
  417. "2022-blake3-aes-256-gcm": {},
  418. "2022-blake3-chacha20-poly1305": {},
  419. }
  420. // shadowsocksCipherName resolves the cipher a shadowsocks user's account must
  421. // be built for. Panel-built user maps carry it under "cipher"; client objects
  422. // taken verbatim from an inbound's settings carry the inbound's method under
  423. // "method" instead (HealShadowsocksClientMethods writes it onto every
  424. // legacy-cipher client).
  425. func shadowsocksCipherName(user map[string]any) (string, error) {
  426. cipher, err := getOptionalUserString(user, "cipher")
  427. if err != nil {
  428. return "", err
  429. }
  430. if cipher != "" {
  431. return cipher, nil
  432. }
  433. return getOptionalUserString(user, "method")
  434. }
  435. // reverseTag reads a vless reverse proxy tag from either shape a caller can
  436. // carry: the settings JSON object, or a typed client value marshalling alike.
  437. func reverseTag(value any) string {
  438. if value == nil {
  439. return ""
  440. }
  441. raw, err := json.Marshal(value)
  442. if err != nil {
  443. return ""
  444. }
  445. var parsed struct {
  446. Tag string `json:"tag"`
  447. }
  448. if json.Unmarshal(raw, &parsed) != nil {
  449. return ""
  450. }
  451. return parsed.Tag
  452. }
  453. // shadowsocksCipherType mirrors xray-core's infra/conf cipherFromString,
  454. // aliases and case-insensitivity included, so the account the panel builds for
  455. // a live user matches the one the core built for that inbound from its config.
  456. func shadowsocksCipherType(cipher string) shadowsocks.CipherType {
  457. switch strings.ToLower(cipher) {
  458. case "aes-128-gcm", "aead_aes_128_gcm":
  459. return shadowsocks.CipherType_AES_128_GCM
  460. case "aes-256-gcm", "aead_aes_256_gcm":
  461. return shadowsocks.CipherType_AES_256_GCM
  462. case "chacha20-poly1305", "aead_chacha20_poly1305", "chacha20-ietf-poly1305":
  463. return shadowsocks.CipherType_CHACHA20_POLY1305
  464. case "xchacha20-poly1305", "aead_xchacha20_poly1305", "xchacha20-ietf-poly1305":
  465. return shadowsocks.CipherType_XCHACHA20_POLY1305
  466. default:
  467. return shadowsocks.CipherType_UNKNOWN
  468. }
  469. }
  470. // isShadowsocks2022Cipher reports whether the method selects the
  471. // shadowsocks-2022 inbound rather than the legacy AEAD one.
  472. func isShadowsocks2022Cipher(cipher string) bool {
  473. _, ok := shadowsocks2022Ciphers[strings.ToLower(cipher)]
  474. return ok
  475. }
  476. // buildUserAccount constructs the typed xray account for a user of the given
  477. // protocol. It returns (nil, nil) for protocols that cannot be altered live so
  478. // callers skip the AlterInbound call. WireGuard keys must be converted to the
  479. // hex form xray's wireguard proxy expects (its ParseKey uses hex.DecodeString),
  480. // unlike the file-config path which accepts base64 and converts internally.
  481. // Shadowsocks is resolved strictly from the inbound's cipher: the legacy and
  482. // 2022 inbounds take different account types and cast whatever they receive
  483. // without checking, so an unrecognized cipher is an error rather than a guess
  484. // that would panic the core and kill every connection on the server.
  485. func buildUserAccount(protocolName string, user map[string]any) (*serial.TypedMessage, error) {
  486. switch protocolName {
  487. case "vmess":
  488. userID, err := getRequiredUserString(user, "id")
  489. if err != nil {
  490. return nil, err
  491. }
  492. return serial.ToTypedMessage(&vmess.Account{
  493. Id: userID,
  494. }), nil
  495. case "vless":
  496. userID, err := getRequiredUserString(user, "id")
  497. if err != nil {
  498. return nil, err
  499. }
  500. userFlow, err := getOptionalUserString(user, "flow")
  501. if err != nil {
  502. return nil, err
  503. }
  504. vlessAccount := &vless.Account{
  505. Id: userID,
  506. Flow: userFlow,
  507. }
  508. // RemoveUser also drops the account's reverse outbound handler, and
  509. // GetReverse only rebuilds it from the tag a re-added account carries.
  510. if tag := reverseTag(user["reverse"]); tag != "" {
  511. vlessAccount.Reverse = &vless.Reverse{Tag: tag}
  512. }
  513. if testseedVal, ok := user["testseed"]; ok {
  514. if testseedArr, ok := testseedVal.([]any); ok && len(testseedArr) >= 4 {
  515. testseed := make([]uint32, len(testseedArr))
  516. for i, v := range testseedArr {
  517. if num, ok := v.(float64); ok {
  518. testseed[i] = uint32(num)
  519. }
  520. }
  521. vlessAccount.Testseed = testseed
  522. } else if testseedArr, ok := testseedVal.([]uint32); ok && len(testseedArr) >= 4 {
  523. vlessAccount.Testseed = testseedArr
  524. }
  525. }
  526. if testpreVal, ok := user["testpre"]; ok {
  527. if testpre, ok := testpreVal.(float64); ok && testpre > 0 {
  528. vlessAccount.Testpre = uint32(testpre)
  529. } else if testpre, ok := testpreVal.(uint32); ok && testpre > 0 {
  530. vlessAccount.Testpre = testpre
  531. }
  532. }
  533. return serial.ToTypedMessage(vlessAccount), nil
  534. case "trojan":
  535. password, err := getRequiredUserString(user, "password")
  536. if err != nil {
  537. return nil, err
  538. }
  539. return serial.ToTypedMessage(&trojan.Account{
  540. Password: password,
  541. }), nil
  542. case "shadowsocks":
  543. cipher, err := shadowsocksCipherName(user)
  544. if err != nil {
  545. return nil, err
  546. }
  547. password, err := getRequiredUserString(user, "password")
  548. if err != nil {
  549. return nil, err
  550. }
  551. if isShadowsocks2022Cipher(cipher) {
  552. return serial.ToTypedMessage(&shadowsocks_2022.Account{
  553. Key: password,
  554. }), nil
  555. }
  556. ssCipherType := shadowsocksCipherType(cipher)
  557. if ssCipherType == shadowsocks.CipherType_UNKNOWN {
  558. return nil, common.NewErrorf("shadowsocks: unknown cipher %q, cannot build an account for the running inbound", cipher)
  559. }
  560. return serial.ToTypedMessage(&shadowsocks.Account{
  561. Password: password,
  562. CipherType: ssCipherType,
  563. }), nil
  564. case "hysteria":
  565. auth, err := getRequiredUserString(user, "auth")
  566. if err != nil {
  567. return nil, err
  568. }
  569. return serial.ToTypedMessage(&hysteriaAccount.Account{
  570. Auth: auth,
  571. }), nil
  572. case "wireguard":
  573. pubB64, err := getRequiredUserString(user, "publicKey")
  574. if err != nil {
  575. return nil, err
  576. }
  577. pubHex, err := wgutil.KeyToHex(pubB64)
  578. if err != nil {
  579. return nil, fmt.Errorf("wireguard publicKey: %w", err)
  580. }
  581. pskB64, err := getOptionalUserString(user, "preSharedKey")
  582. if err != nil {
  583. return nil, err
  584. }
  585. pskHex, err := wgutil.KeyToHex(pskB64)
  586. if err != nil {
  587. return nil, fmt.Errorf("wireguard preSharedKey: %w", err)
  588. }
  589. allowed := collectStringSlice(user["allowedIPs"])
  590. if len(allowed) == 0 {
  591. return nil, common.NewError("wireguard: allowedIPs required")
  592. }
  593. keepAlive, err := getOptionalUserString(user, "keepAlive")
  594. if err != nil {
  595. return nil, err
  596. }
  597. return serial.ToTypedMessage(&wireguard.PeerConfig{
  598. PublicKey: pubHex,
  599. PreSharedKey: pskHex,
  600. AllowedIps: allowed,
  601. KeepAlive: keepAlive,
  602. }), nil
  603. default:
  604. return nil, nil
  605. }
  606. }
  607. // AddUser adds a user to an inbound in the Xray core using the specified
  608. // protocol and user data. On a legacy shadowsocks inbound the add first drops
  609. // any existing holder of the email: that is the one inbound whose validator
  610. // does not reject a duplicate email, and a later removal would then drop just
  611. // one of the two registrations, leaving a disabled client able to connect.
  612. func (x *XrayAPI) AddUser(Protocol string, inboundTag string, user map[string]any) error {
  613. userEmail, err := getRequiredUserString(user, "email")
  614. if err != nil {
  615. return err
  616. }
  617. account, err := buildUserAccount(Protocol, user)
  618. if err != nil {
  619. return err
  620. }
  621. if account == nil {
  622. return nil
  623. }
  624. if x.HandlerServiceClient == nil {
  625. return common.NewError("xray HandlerServiceClient is not initialized")
  626. }
  627. client := *x.HandlerServiceClient
  628. if account.Type == legacyShadowsocksAccountType {
  629. _ = x.RemoveUser(inboundTag, userEmail)
  630. }
  631. ctx, cancel := context.WithTimeout(context.Background(), handlerRPCTimeout)
  632. defer cancel()
  633. _, err = client.AlterInbound(ctx, &command.AlterInboundRequest{
  634. Tag: inboundTag,
  635. Operation: serial.ToTypedMessage(&command.AddUserOperation{
  636. User: &protocol.User{
  637. Email: userEmail,
  638. Account: account,
  639. },
  640. }),
  641. })
  642. return err
  643. }
  644. // RemoveUser removes a user from an inbound in the Xray core by email.
  645. func (x *XrayAPI) RemoveUser(inboundTag, email string) error {
  646. if x.HandlerServiceClient == nil {
  647. return common.NewError("xray HandlerServiceClient is not initialized")
  648. }
  649. client := *x.HandlerServiceClient
  650. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  651. defer cancel()
  652. op := &command.RemoveUserOperation{Email: email}
  653. req := &command.AlterInboundRequest{
  654. Tag: inboundTag,
  655. Operation: serial.ToTypedMessage(op),
  656. }
  657. _, err := client.AlterInbound(ctx, req)
  658. if err != nil {
  659. return fmt.Errorf("failed to remove user: %w", err)
  660. }
  661. return nil
  662. }
  663. // GetTraffic queries traffic statistics from the Xray core and reports what
  664. // accrued since the previous call; the counters themselves are never reset.
  665. // The first call of a process only records baselines, since it may be reading
  666. // counters that already hold traffic the panel cannot attribute. After that a
  667. // name the panel has not seen — xray creates a counter on a user's first use —
  668. // and a counter that moved backwards because the core restarted both count
  669. // from zero, so no client's traffic is dropped for a whole polling interval.
  670. func (x *XrayAPI) GetTraffic() ([]*Traffic, []*ClientTraffic, error) {
  671. if x.grpcClient == nil {
  672. return nil, nil, common.NewError("xray api is not initialized")
  673. }
  674. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  675. defer cancel()
  676. if x.StatsServiceClient == nil {
  677. return nil, nil, common.NewError("xray StatusServiceClient is not initialized")
  678. }
  679. resp, err := (*x.StatsServiceClient).QueryStats(ctx, &statsService.QueryStatsRequest{Reset_: false})
  680. if err != nil {
  681. logger.Debug("Failed to query Xray stats:", err)
  682. return nil, nil, err
  683. }
  684. tagTrafficMap := make(map[string]*Traffic)
  685. emailTrafficMap := make(map[string]*ClientTraffic)
  686. baselinePass := len(x.StatsLastValues) == 0
  687. for _, stat := range resp.GetStat() {
  688. lastValue, ok := x.StatsLastValues[stat.Name]
  689. x.StatsLastValues[stat.Name] = stat.Value
  690. if baselinePass {
  691. continue
  692. }
  693. if !ok || stat.Value < lastValue {
  694. lastValue = 0
  695. }
  696. value := stat.Value - lastValue
  697. if matches := trafficRegex.FindStringSubmatch(stat.Name); len(matches) == 4 {
  698. processTraffic(matches, value, tagTrafficMap)
  699. } else if matches := clientTrafficRegex.FindStringSubmatch(stat.Name); len(matches) == 3 {
  700. processClientTraffic(matches, value, emailTrafficMap)
  701. }
  702. }
  703. // Drop delta baselines for stats that no longer exist (deleted inbounds or
  704. // clients), which otherwise linger until the next Xray restart. Only rebuild
  705. // when the map has drifted past 2x the live set, so the steady-state hot path
  706. // stays allocation-free.
  707. if n := len(resp.GetStat()); n > 0 && len(x.StatsLastValues) > 2*n {
  708. pruned := make(map[string]int64, n)
  709. for _, stat := range resp.GetStat() {
  710. pruned[stat.Name] = x.StatsLastValues[stat.Name]
  711. }
  712. x.StatsLastValues = pruned
  713. }
  714. return mapToSlice(tagTrafficMap), mapToSlice(emailTrafficMap), nil
  715. }
  716. // OnlineIP is one source address of a live connection, with the unix time (seconds)
  717. // the core last dispatched a link from it.
  718. type OnlineIP struct {
  719. IP string `json:"ip"`
  720. LastSeen int64 `json:"lastSeen"`
  721. }
  722. // OnlineUser is a client email with at least one live connection and the source
  723. // IPs of those connections, as tracked by Xray's statsUserOnline policy.
  724. type OnlineUser struct {
  725. Email string `json:"email"`
  726. IPs []OnlineIP `json:"ips"`
  727. }
  728. // GetOnlineUsers returns every user with at least one live connection plus their
  729. // source IPs, via StatsService.GetUsersStats (one RPC covers all users). Requires
  730. // statsUserOnline enabled in the policy levels; older cores return Unimplemented.
  731. func (x *XrayAPI) GetOnlineUsers() ([]OnlineUser, error) {
  732. if x.grpcClient == nil {
  733. return nil, common.NewError("xray api is not initialized")
  734. }
  735. if x.StatsServiceClient == nil {
  736. return nil, common.NewError("xray StatsServiceClient is not initialized")
  737. }
  738. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  739. defer cancel()
  740. resp, err := (*x.StatsServiceClient).GetUsersStats(ctx, &statsService.GetUsersStatsRequest{})
  741. if err != nil {
  742. return nil, err
  743. }
  744. users := make([]OnlineUser, 0, len(resp.GetUsers()))
  745. for _, u := range resp.GetUsers() {
  746. if u == nil || u.GetEmail() == "" {
  747. continue
  748. }
  749. ips := make([]OnlineIP, 0, len(u.GetIps()))
  750. for _, entry := range u.GetIps() {
  751. if entry == nil || entry.GetIp() == "" {
  752. continue
  753. }
  754. ips = append(ips, OnlineIP{IP: entry.GetIp(), LastSeen: entry.GetLastSeen()})
  755. }
  756. users = append(users, OnlineUser{Email: u.GetEmail(), IPs: ips})
  757. }
  758. return users, nil
  759. }
  760. // IsUnimplementedErr reports whether err is the running core saying it lacks an
  761. // RPC (an older Xray binary without the online-stats API).
  762. func IsUnimplementedErr(err error) bool {
  763. return status.Code(err) == codes.Unimplemented
  764. }
  765. // processTraffic aggregates a traffic stat into trafficMap using regex matches and value.
  766. func processTraffic(matches []string, value int64, trafficMap map[string]*Traffic) {
  767. isInbound := matches[1] == "inbound"
  768. tag := matches[2]
  769. isDown := matches[3] == "downlink"
  770. if tag == "api" {
  771. return
  772. }
  773. traffic, ok := trafficMap[tag]
  774. if !ok {
  775. traffic = &Traffic{
  776. IsInbound: isInbound,
  777. IsOutbound: !isInbound,
  778. Tag: tag,
  779. }
  780. trafficMap[tag] = traffic
  781. }
  782. if isDown {
  783. traffic.Down = value
  784. } else {
  785. traffic.Up = value
  786. }
  787. }
  788. // processClientTraffic updates clientTrafficMap with upload/download values for a client email.
  789. func processClientTraffic(matches []string, value int64, clientTrafficMap map[string]*ClientTraffic) {
  790. email := matches[1]
  791. isDown := matches[2] == "downlink"
  792. traffic, ok := clientTrafficMap[email]
  793. if !ok {
  794. traffic = &ClientTraffic{Email: email}
  795. clientTrafficMap[email] = traffic
  796. }
  797. if isDown {
  798. traffic.Down = value
  799. } else {
  800. traffic.Up = value
  801. }
  802. }
  803. // mapToSlice converts a map of pointers to a slice of pointers.
  804. func mapToSlice[T any](m map[string]*T) []*T {
  805. result := make([]*T, 0, len(m))
  806. for _, v := range m {
  807. result = append(result, v)
  808. }
  809. return result
  810. }