api.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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. // shadowsocksCipherType mirrors xray-core's infra/conf cipherFromString,
  436. // aliases and case-insensitivity included, so the account the panel builds for
  437. // a live user matches the one the core built for that inbound from its config.
  438. func shadowsocksCipherType(cipher string) shadowsocks.CipherType {
  439. switch strings.ToLower(cipher) {
  440. case "aes-128-gcm", "aead_aes_128_gcm":
  441. return shadowsocks.CipherType_AES_128_GCM
  442. case "aes-256-gcm", "aead_aes_256_gcm":
  443. return shadowsocks.CipherType_AES_256_GCM
  444. case "chacha20-poly1305", "aead_chacha20_poly1305", "chacha20-ietf-poly1305":
  445. return shadowsocks.CipherType_CHACHA20_POLY1305
  446. case "xchacha20-poly1305", "aead_xchacha20_poly1305", "xchacha20-ietf-poly1305":
  447. return shadowsocks.CipherType_XCHACHA20_POLY1305
  448. default:
  449. return shadowsocks.CipherType_UNKNOWN
  450. }
  451. }
  452. // isShadowsocks2022Cipher reports whether the method selects the
  453. // shadowsocks-2022 inbound rather than the legacy AEAD one.
  454. func isShadowsocks2022Cipher(cipher string) bool {
  455. _, ok := shadowsocks2022Ciphers[strings.ToLower(cipher)]
  456. return ok
  457. }
  458. // buildUserAccount constructs the typed xray account for a user of the given
  459. // protocol. It returns (nil, nil) for protocols that cannot be altered live so
  460. // callers skip the AlterInbound call. WireGuard keys must be converted to the
  461. // hex form xray's wireguard proxy expects (its ParseKey uses hex.DecodeString),
  462. // unlike the file-config path which accepts base64 and converts internally.
  463. // Shadowsocks is resolved strictly from the inbound's cipher: the legacy and
  464. // 2022 inbounds take different account types and cast whatever they receive
  465. // without checking, so an unrecognized cipher is an error rather than a guess
  466. // that would panic the core and kill every connection on the server.
  467. func buildUserAccount(protocolName string, user map[string]any) (*serial.TypedMessage, error) {
  468. switch protocolName {
  469. case "vmess":
  470. userID, err := getRequiredUserString(user, "id")
  471. if err != nil {
  472. return nil, err
  473. }
  474. return serial.ToTypedMessage(&vmess.Account{
  475. Id: userID,
  476. }), nil
  477. case "vless":
  478. userID, err := getRequiredUserString(user, "id")
  479. if err != nil {
  480. return nil, err
  481. }
  482. userFlow, err := getOptionalUserString(user, "flow")
  483. if err != nil {
  484. return nil, err
  485. }
  486. vlessAccount := &vless.Account{
  487. Id: userID,
  488. Flow: userFlow,
  489. }
  490. if testseedVal, ok := user["testseed"]; ok {
  491. if testseedArr, ok := testseedVal.([]any); ok && len(testseedArr) >= 4 {
  492. testseed := make([]uint32, len(testseedArr))
  493. for i, v := range testseedArr {
  494. if num, ok := v.(float64); ok {
  495. testseed[i] = uint32(num)
  496. }
  497. }
  498. vlessAccount.Testseed = testseed
  499. } else if testseedArr, ok := testseedVal.([]uint32); ok && len(testseedArr) >= 4 {
  500. vlessAccount.Testseed = testseedArr
  501. }
  502. }
  503. if testpreVal, ok := user["testpre"]; ok {
  504. if testpre, ok := testpreVal.(float64); ok && testpre > 0 {
  505. vlessAccount.Testpre = uint32(testpre)
  506. } else if testpre, ok := testpreVal.(uint32); ok && testpre > 0 {
  507. vlessAccount.Testpre = testpre
  508. }
  509. }
  510. return serial.ToTypedMessage(vlessAccount), nil
  511. case "trojan":
  512. password, err := getRequiredUserString(user, "password")
  513. if err != nil {
  514. return nil, err
  515. }
  516. return serial.ToTypedMessage(&trojan.Account{
  517. Password: password,
  518. }), nil
  519. case "shadowsocks":
  520. cipher, err := shadowsocksCipherName(user)
  521. if err != nil {
  522. return nil, err
  523. }
  524. password, err := getRequiredUserString(user, "password")
  525. if err != nil {
  526. return nil, err
  527. }
  528. if isShadowsocks2022Cipher(cipher) {
  529. return serial.ToTypedMessage(&shadowsocks_2022.Account{
  530. Key: password,
  531. }), nil
  532. }
  533. ssCipherType := shadowsocksCipherType(cipher)
  534. if ssCipherType == shadowsocks.CipherType_UNKNOWN {
  535. return nil, common.NewErrorf("shadowsocks: unknown cipher %q, cannot build an account for the running inbound", cipher)
  536. }
  537. return serial.ToTypedMessage(&shadowsocks.Account{
  538. Password: password,
  539. CipherType: ssCipherType,
  540. }), nil
  541. case "hysteria":
  542. auth, err := getRequiredUserString(user, "auth")
  543. if err != nil {
  544. return nil, err
  545. }
  546. return serial.ToTypedMessage(&hysteriaAccount.Account{
  547. Auth: auth,
  548. }), nil
  549. case "wireguard":
  550. pubB64, err := getRequiredUserString(user, "publicKey")
  551. if err != nil {
  552. return nil, err
  553. }
  554. pubHex, err := wgutil.KeyToHex(pubB64)
  555. if err != nil {
  556. return nil, fmt.Errorf("wireguard publicKey: %w", err)
  557. }
  558. pskB64, err := getOptionalUserString(user, "preSharedKey")
  559. if err != nil {
  560. return nil, err
  561. }
  562. pskHex, err := wgutil.KeyToHex(pskB64)
  563. if err != nil {
  564. return nil, fmt.Errorf("wireguard preSharedKey: %w", err)
  565. }
  566. allowed := collectStringSlice(user["allowedIPs"])
  567. if len(allowed) == 0 {
  568. return nil, common.NewError("wireguard: allowedIPs required")
  569. }
  570. keepAlive, err := getOptionalUserString(user, "keepAlive")
  571. if err != nil {
  572. return nil, err
  573. }
  574. return serial.ToTypedMessage(&wireguard.PeerConfig{
  575. PublicKey: pubHex,
  576. PreSharedKey: pskHex,
  577. AllowedIps: allowed,
  578. KeepAlive: keepAlive,
  579. }), nil
  580. default:
  581. return nil, nil
  582. }
  583. }
  584. // AddUser adds a user to an inbound in the Xray core using the specified
  585. // protocol and user data. On a legacy shadowsocks inbound the add first drops
  586. // any existing holder of the email: that is the one inbound whose validator
  587. // does not reject a duplicate email, and a later removal would then drop just
  588. // one of the two registrations, leaving a disabled client able to connect.
  589. func (x *XrayAPI) AddUser(Protocol string, inboundTag string, user map[string]any) error {
  590. userEmail, err := getRequiredUserString(user, "email")
  591. if err != nil {
  592. return err
  593. }
  594. account, err := buildUserAccount(Protocol, user)
  595. if err != nil {
  596. return err
  597. }
  598. if account == nil {
  599. return nil
  600. }
  601. if x.HandlerServiceClient == nil {
  602. return common.NewError("xray HandlerServiceClient is not initialized")
  603. }
  604. client := *x.HandlerServiceClient
  605. if account.Type == legacyShadowsocksAccountType {
  606. _ = x.RemoveUser(inboundTag, userEmail)
  607. }
  608. ctx, cancel := context.WithTimeout(context.Background(), handlerRPCTimeout)
  609. defer cancel()
  610. _, err = client.AlterInbound(ctx, &command.AlterInboundRequest{
  611. Tag: inboundTag,
  612. Operation: serial.ToTypedMessage(&command.AddUserOperation{
  613. User: &protocol.User{
  614. Email: userEmail,
  615. Account: account,
  616. },
  617. }),
  618. })
  619. return err
  620. }
  621. // RemoveUser removes a user from an inbound in the Xray core by email.
  622. func (x *XrayAPI) RemoveUser(inboundTag, email string) error {
  623. if x.HandlerServiceClient == nil {
  624. return common.NewError("xray HandlerServiceClient is not initialized")
  625. }
  626. client := *x.HandlerServiceClient
  627. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  628. defer cancel()
  629. op := &command.RemoveUserOperation{Email: email}
  630. req := &command.AlterInboundRequest{
  631. Tag: inboundTag,
  632. Operation: serial.ToTypedMessage(op),
  633. }
  634. _, err := client.AlterInbound(ctx, req)
  635. if err != nil {
  636. return fmt.Errorf("failed to remove user: %w", err)
  637. }
  638. return nil
  639. }
  640. // GetTraffic queries traffic statistics from the Xray core and reports what
  641. // accrued since the previous call; the counters themselves are never reset.
  642. // The first call of a process only records baselines, since it may be reading
  643. // counters that already hold traffic the panel cannot attribute. After that a
  644. // name the panel has not seen — xray creates a counter on a user's first use —
  645. // and a counter that moved backwards because the core restarted both count
  646. // from zero, so no client's traffic is dropped for a whole polling interval.
  647. func (x *XrayAPI) GetTraffic() ([]*Traffic, []*ClientTraffic, error) {
  648. if x.grpcClient == nil {
  649. return nil, nil, common.NewError("xray api is not initialized")
  650. }
  651. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  652. defer cancel()
  653. if x.StatsServiceClient == nil {
  654. return nil, nil, common.NewError("xray StatusServiceClient is not initialized")
  655. }
  656. resp, err := (*x.StatsServiceClient).QueryStats(ctx, &statsService.QueryStatsRequest{Reset_: false})
  657. if err != nil {
  658. logger.Debug("Failed to query Xray stats:", err)
  659. return nil, nil, err
  660. }
  661. tagTrafficMap := make(map[string]*Traffic)
  662. emailTrafficMap := make(map[string]*ClientTraffic)
  663. baselinePass := len(x.StatsLastValues) == 0
  664. for _, stat := range resp.GetStat() {
  665. lastValue, ok := x.StatsLastValues[stat.Name]
  666. x.StatsLastValues[stat.Name] = stat.Value
  667. if baselinePass {
  668. continue
  669. }
  670. if !ok || stat.Value < lastValue {
  671. lastValue = 0
  672. }
  673. value := stat.Value - lastValue
  674. if matches := trafficRegex.FindStringSubmatch(stat.Name); len(matches) == 4 {
  675. processTraffic(matches, value, tagTrafficMap)
  676. } else if matches := clientTrafficRegex.FindStringSubmatch(stat.Name); len(matches) == 3 {
  677. processClientTraffic(matches, value, emailTrafficMap)
  678. }
  679. }
  680. // Drop delta baselines for stats that no longer exist (deleted inbounds or
  681. // clients), which otherwise linger until the next Xray restart. Only rebuild
  682. // when the map has drifted past 2x the live set, so the steady-state hot path
  683. // stays allocation-free.
  684. if n := len(resp.GetStat()); n > 0 && len(x.StatsLastValues) > 2*n {
  685. pruned := make(map[string]int64, n)
  686. for _, stat := range resp.GetStat() {
  687. pruned[stat.Name] = x.StatsLastValues[stat.Name]
  688. }
  689. x.StatsLastValues = pruned
  690. }
  691. return mapToSlice(tagTrafficMap), mapToSlice(emailTrafficMap), nil
  692. }
  693. // OnlineIP is one source address of a live connection, with the unix time (seconds)
  694. // the core last dispatched a link from it.
  695. type OnlineIP struct {
  696. IP string `json:"ip"`
  697. LastSeen int64 `json:"lastSeen"`
  698. }
  699. // OnlineUser is a client email with at least one live connection and the source
  700. // IPs of those connections, as tracked by Xray's statsUserOnline policy.
  701. type OnlineUser struct {
  702. Email string `json:"email"`
  703. IPs []OnlineIP `json:"ips"`
  704. }
  705. // GetOnlineUsers returns every user with at least one live connection plus their
  706. // source IPs, via StatsService.GetUsersStats (one RPC covers all users). Requires
  707. // statsUserOnline enabled in the policy levels; older cores return Unimplemented.
  708. func (x *XrayAPI) GetOnlineUsers() ([]OnlineUser, error) {
  709. if x.grpcClient == nil {
  710. return nil, common.NewError("xray api is not initialized")
  711. }
  712. if x.StatsServiceClient == nil {
  713. return nil, common.NewError("xray StatsServiceClient is not initialized")
  714. }
  715. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  716. defer cancel()
  717. resp, err := (*x.StatsServiceClient).GetUsersStats(ctx, &statsService.GetUsersStatsRequest{})
  718. if err != nil {
  719. return nil, err
  720. }
  721. users := make([]OnlineUser, 0, len(resp.GetUsers()))
  722. for _, u := range resp.GetUsers() {
  723. if u == nil || u.GetEmail() == "" {
  724. continue
  725. }
  726. ips := make([]OnlineIP, 0, len(u.GetIps()))
  727. for _, entry := range u.GetIps() {
  728. if entry == nil || entry.GetIp() == "" {
  729. continue
  730. }
  731. ips = append(ips, OnlineIP{IP: entry.GetIp(), LastSeen: entry.GetLastSeen()})
  732. }
  733. users = append(users, OnlineUser{Email: u.GetEmail(), IPs: ips})
  734. }
  735. return users, nil
  736. }
  737. // IsUnimplementedErr reports whether err is the running core saying it lacks an
  738. // RPC (an older Xray binary without the online-stats API).
  739. func IsUnimplementedErr(err error) bool {
  740. return status.Code(err) == codes.Unimplemented
  741. }
  742. // processTraffic aggregates a traffic stat into trafficMap using regex matches and value.
  743. func processTraffic(matches []string, value int64, trafficMap map[string]*Traffic) {
  744. isInbound := matches[1] == "inbound"
  745. tag := matches[2]
  746. isDown := matches[3] == "downlink"
  747. if tag == "api" {
  748. return
  749. }
  750. traffic, ok := trafficMap[tag]
  751. if !ok {
  752. traffic = &Traffic{
  753. IsInbound: isInbound,
  754. IsOutbound: !isInbound,
  755. Tag: tag,
  756. }
  757. trafficMap[tag] = traffic
  758. }
  759. if isDown {
  760. traffic.Down = value
  761. } else {
  762. traffic.Up = value
  763. }
  764. }
  765. // processClientTraffic updates clientTrafficMap with upload/download values for a client email.
  766. func processClientTraffic(matches []string, value int64, clientTrafficMap map[string]*ClientTraffic) {
  767. email := matches[1]
  768. isDown := matches[2] == "downlink"
  769. traffic, ok := clientTrafficMap[email]
  770. if !ok {
  771. traffic = &ClientTraffic{Email: email}
  772. clientTrafficMap[email] = traffic
  773. }
  774. if isDown {
  775. traffic.Down = value
  776. } else {
  777. traffic.Up = value
  778. }
  779. }
  780. // mapToSlice converts a map of pointers to a slice of pointers.
  781. func mapToSlice[T any](m map[string]*T) []*T {
  782. result := make([]*T, 0, len(m))
  783. for _, v := range m {
  784. result = append(result, v)
  785. }
  786. return result
  787. }