api.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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. "net/netip"
  12. "os"
  13. "path/filepath"
  14. "regexp"
  15. "strings"
  16. "time"
  17. "github.com/mhsanaei/3x-ui/v3/internal/config"
  18. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  19. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  20. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  21. "github.com/xtls/xray-core/app/proxyman/command"
  22. routerService "github.com/xtls/xray-core/app/router/command"
  23. statsService "github.com/xtls/xray-core/app/stats/command"
  24. xnet "github.com/xtls/xray-core/common/net"
  25. "github.com/xtls/xray-core/common/protocol"
  26. "github.com/xtls/xray-core/common/serial"
  27. "github.com/xtls/xray-core/infra/conf"
  28. hysteriaAccount "github.com/xtls/xray-core/proxy/hysteria/account"
  29. "github.com/xtls/xray-core/proxy/shadowsocks"
  30. "github.com/xtls/xray-core/proxy/shadowsocks_2022"
  31. "github.com/xtls/xray-core/proxy/trojan"
  32. "github.com/xtls/xray-core/proxy/vless"
  33. "github.com/xtls/xray-core/proxy/vmess"
  34. wireguard "github.com/xtls/xray-core/proxy/wireguard"
  35. "google.golang.org/grpc"
  36. "google.golang.org/grpc/codes"
  37. "google.golang.org/grpc/credentials/insecure"
  38. "google.golang.org/grpc/status"
  39. )
  40. // Compiled once at package load: GetTraffic runs on every traffic-stats tick,
  41. // so recompiling these per call is wasted work.
  42. var (
  43. trafficRegex = regexp.MustCompile(`(inbound|outbound)>>>([^>]+)>>>traffic>>>(downlink|uplink)`)
  44. clientTrafficRegex = regexp.MustCompile(`user>>>([^>]+)>>>traffic>>>(downlink|uplink)`)
  45. )
  46. // XrayAPI is a gRPC client for managing Xray core configuration, inbounds, outbounds, and statistics.
  47. type XrayAPI struct {
  48. HandlerServiceClient *command.HandlerServiceClient
  49. StatsServiceClient *statsService.StatsServiceClient
  50. RoutingServiceClient *routerService.RoutingServiceClient
  51. grpcClient *grpc.ClientConn
  52. isConnected bool
  53. StatsLastValues map[string]int64
  54. }
  55. func getRequiredUserString(user map[string]any, key string) (string, error) {
  56. value, ok := user[key]
  57. if !ok || value == nil {
  58. return "", fmt.Errorf("missing required user field %q", key)
  59. }
  60. strValue, ok := value.(string)
  61. if !ok {
  62. return "", fmt.Errorf("invalid type for user field %q: %T", key, value)
  63. }
  64. return strValue, nil
  65. }
  66. func getOptionalUserString(user map[string]any, key string) (string, error) {
  67. value, ok := user[key]
  68. if !ok || value == nil {
  69. return "", nil
  70. }
  71. strValue, ok := value.(string)
  72. if !ok {
  73. return "", fmt.Errorf("invalid type for user field %q: %T", key, value)
  74. }
  75. return strValue, nil
  76. }
  77. // Init connects to the Xray API server and initializes handler and stats service clients.
  78. func (x *XrayAPI) Init(apiPort int) error {
  79. if apiPort <= 0 || apiPort > math.MaxUint16 {
  80. return fmt.Errorf("invalid Xray API port: %d", apiPort)
  81. }
  82. addr := fmt.Sprintf("127.0.0.1:%d", apiPort)
  83. conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
  84. if err != nil {
  85. return fmt.Errorf("failed to connect to Xray API: %w", err)
  86. }
  87. x.grpcClient = conn
  88. x.isConnected = true
  89. if x.StatsLastValues == nil {
  90. x.StatsLastValues = make(map[string]int64)
  91. }
  92. hsClient := command.NewHandlerServiceClient(conn)
  93. ssClient := statsService.NewStatsServiceClient(conn)
  94. rsClient := routerService.NewRoutingServiceClient(conn)
  95. x.HandlerServiceClient = &hsClient
  96. x.StatsServiceClient = &ssClient
  97. x.RoutingServiceClient = &rsClient
  98. return nil
  99. }
  100. // Close closes the gRPC connection and resets the XrayAPI client state.
  101. func (x *XrayAPI) Close() {
  102. if x.grpcClient != nil {
  103. x.grpcClient.Close()
  104. }
  105. x.HandlerServiceClient = nil
  106. x.StatsServiceClient = nil
  107. x.RoutingServiceClient = nil
  108. x.isConnected = false
  109. }
  110. // handlerRPCTimeout bounds per-call gRPC handler operations (add/remove inbound,
  111. // alter user) so a hung core connection cannot block the caller indefinitely —
  112. // for example while the process restart lock is held.
  113. const handlerRPCTimeout = 10 * time.Second
  114. // AddInbound adds a new inbound configuration to the Xray core via gRPC.
  115. func (x *XrayAPI) AddInbound(inbound []byte) error {
  116. if x.HandlerServiceClient == nil {
  117. return common.NewError("xray HandlerServiceClient is not initialized")
  118. }
  119. client := *x.HandlerServiceClient
  120. conf := new(conf.InboundDetourConfig)
  121. err := json.Unmarshal(inbound, conf)
  122. if err != nil {
  123. logger.Debug("Failed to unmarshal inbound:", err)
  124. return err
  125. }
  126. config, err := conf.Build()
  127. if err != nil {
  128. logger.Debug("Failed to build inbound Detur:", err)
  129. return err
  130. }
  131. inboundConfig := command.AddInboundRequest{Inbound: config}
  132. ctx, cancel := context.WithTimeout(context.Background(), handlerRPCTimeout)
  133. defer cancel()
  134. _, err = client.AddInbound(ctx, &inboundConfig)
  135. return err
  136. }
  137. // DelInbound removes an inbound configuration from the Xray core by tag.
  138. func (x *XrayAPI) DelInbound(tag string) error {
  139. if x.HandlerServiceClient == nil {
  140. return common.NewError("xray HandlerServiceClient is not initialized")
  141. }
  142. client := *x.HandlerServiceClient
  143. ctx, cancel := context.WithTimeout(context.Background(), handlerRPCTimeout)
  144. defer cancel()
  145. _, err := client.RemoveInbound(ctx, &command.RemoveInboundRequest{
  146. Tag: tag,
  147. })
  148. return err
  149. }
  150. // ValidateOutboundConfig builds an outbound JSON object through the vendored
  151. // xray-core config loader, surfacing the exact error the core would raise at
  152. // startup — notably v26.7.11's refusal of unencrypted vless/trojan outbounds
  153. // whose server address is a public IP or domain.
  154. func ValidateOutboundConfig(outbound []byte) error {
  155. ensureXrayAssetLocation()
  156. detour := new(conf.OutboundDetourConfig)
  157. if err := json.Unmarshal(outbound, detour); err != nil {
  158. return err
  159. }
  160. built, err := detour.Build()
  161. if err != nil {
  162. return err
  163. }
  164. return validateWireguardRemoteDNS(built.ProxySettings)
  165. }
  166. // validateWireguardRemoteDNS refuses what conf.Build() lets through but the core feeds to
  167. // netip.MustParseAddr at startup: a non-IP remoteDNS entry, like "local" before 26.9.30.
  168. func validateWireguardRemoteDNS(settings *serial.TypedMessage) error {
  169. if settings == nil {
  170. return nil
  171. }
  172. instance, err := settings.GetInstance()
  173. if err != nil {
  174. return nil
  175. }
  176. device, ok := instance.(*wireguard.DeviceConfig)
  177. if !ok || !device.IsClient {
  178. return nil
  179. }
  180. for _, server := range device.DNS {
  181. if _, err := netip.ParseAddr(server); err != nil {
  182. return common.NewErrorf("wireguard remoteDNS entry %q is not an IP address", server)
  183. }
  184. }
  185. return nil
  186. }
  187. // AddOutbound adds a new outbound configuration to the Xray core via gRPC.
  188. func (x *XrayAPI) AddOutbound(outbound []byte) error {
  189. if x.HandlerServiceClient == nil {
  190. return common.NewError("xray HandlerServiceClient is not initialized")
  191. }
  192. client := *x.HandlerServiceClient
  193. ensureXrayAssetLocation()
  194. conf := new(conf.OutboundDetourConfig)
  195. if err := json.Unmarshal(outbound, conf); err != nil {
  196. logger.Debug("Failed to unmarshal outbound:", err)
  197. return err
  198. }
  199. config, err := conf.Build()
  200. if err != nil {
  201. logger.Debug("Failed to build outbound detour:", err)
  202. return err
  203. }
  204. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  205. defer cancel()
  206. _, err = client.AddOutbound(ctx, &command.AddOutboundRequest{Outbound: config})
  207. return err
  208. }
  209. // DelOutbound removes an outbound configuration from the Xray core by tag.
  210. func (x *XrayAPI) DelOutbound(tag string) error {
  211. if x.HandlerServiceClient == nil {
  212. return common.NewError("xray HandlerServiceClient is not initialized")
  213. }
  214. client := *x.HandlerServiceClient
  215. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  216. defer cancel()
  217. _, err := client.RemoveOutbound(ctx, &command.RemoveOutboundRequest{Tag: tag})
  218. return err
  219. }
  220. // ApplyRoutingConfig replaces the routing rules and balancers of the running
  221. // Xray core with the given routing section (the JSON value of the top-level
  222. // "routing" key) via the RoutingService gRPC API. Note that this cannot change
  223. // routing.domainStrategy/domainMatcher — those are fixed at process start.
  224. func (x *XrayAPI) ApplyRoutingConfig(routing []byte) error {
  225. if x.RoutingServiceClient == nil {
  226. return common.NewError("xray RoutingServiceClient is not initialized")
  227. }
  228. // Rules referencing geoip:/geosite: need the dat files; point xray-core's
  229. // in-process loader at the panel's bin folder where they live.
  230. ensureXrayAssetLocation()
  231. routerConf := new(conf.RouterConfig)
  232. if err := json.Unmarshal(routing, routerConf); err != nil {
  233. logger.Debug("Failed to unmarshal routing config:", err)
  234. return err
  235. }
  236. config, err := routerConf.Build()
  237. if err != nil {
  238. logger.Debug("Failed to build routing config:", err)
  239. return err
  240. }
  241. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  242. defer cancel()
  243. _, err = (*x.RoutingServiceClient).AddRule(ctx, &routerService.AddRuleRequest{
  244. ShouldAppend: false,
  245. Config: serial.ToTypedMessage(config),
  246. })
  247. return err
  248. }
  249. // BalancerInfo is the live state of one balancer inside the running core.
  250. type BalancerInfo struct {
  251. Tag string `json:"tag"`
  252. // Override is the outbound tag an admin forced via the API; empty when
  253. // the strategy is in control.
  254. Override string `json:"override"`
  255. // Selected are the outbound tags the strategy currently prefers, best
  256. // first (xray's "principle target" list).
  257. Selected []string `json:"selected"`
  258. }
  259. // GetBalancerInfo queries the running core for a balancer's current override
  260. // and the targets its strategy would pick right now.
  261. func (x *XrayAPI) GetBalancerInfo(tag string) (*BalancerInfo, error) {
  262. if x.RoutingServiceClient == nil {
  263. return nil, common.NewError("xray RoutingServiceClient is not initialized")
  264. }
  265. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  266. defer cancel()
  267. resp, err := (*x.RoutingServiceClient).GetBalancerInfo(ctx, &routerService.GetBalancerInfoRequest{Tag: tag})
  268. if err != nil {
  269. return nil, err
  270. }
  271. info := &BalancerInfo{Tag: tag}
  272. if balancer := resp.GetBalancer(); balancer != nil {
  273. if balancer.Override != nil {
  274. info.Override = balancer.Override.Target
  275. }
  276. if balancer.PrincipleTarget != nil {
  277. info.Selected = balancer.PrincipleTarget.Tag
  278. }
  279. }
  280. return info, nil
  281. }
  282. // SetBalancerTarget forces a balancer to always pick the given outbound tag.
  283. // An empty target clears the override and hands control back to the strategy.
  284. func (x *XrayAPI) SetBalancerTarget(tag, target string) error {
  285. if x.RoutingServiceClient == nil {
  286. return common.NewError("xray RoutingServiceClient is not initialized")
  287. }
  288. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  289. defer cancel()
  290. _, err := (*x.RoutingServiceClient).OverrideBalancerTarget(ctx, &routerService.OverrideBalancerTargetRequest{
  291. BalancerTag: tag,
  292. Target: target,
  293. })
  294. return err
  295. }
  296. // RouteTestRequest describes a synthetic connection to ask the running core
  297. // which outbound its router would pick for it.
  298. type RouteTestRequest struct {
  299. InboundTag string // optional: simulate arrival on this inbound
  300. Domain string // target domain (sniffed/SOCKS-style destination)
  301. IP string // target IP, used when Domain is empty or alongside it
  302. Port int
  303. Network string // "tcp" (default) or "udp"
  304. Protocol string // optional sniffed protocol: http, tls, bittorrent, ...
  305. Email string // optional user attribution for user-based rules
  306. }
  307. // RouteTestResult is the routing decision the core reported.
  308. type RouteTestResult struct {
  309. // Matched is false when no routing rule matched — traffic would use the
  310. // default (first) outbound and OutboundTag is empty.
  311. Matched bool `json:"matched"`
  312. OutboundTag string `json:"outboundTag"`
  313. // GroupTags lists the balancer chain the decision went through, when any.
  314. GroupTags []string `json:"groupTags,omitempty"`
  315. }
  316. // TestRoute asks the running core's router which outbound it would pick for
  317. // the described connection, without sending any traffic.
  318. func (x *XrayAPI) TestRoute(req RouteTestRequest) (*RouteTestResult, error) {
  319. if x.RoutingServiceClient == nil {
  320. return nil, common.NewError("xray RoutingServiceClient is not initialized")
  321. }
  322. if req.Port < 0 || req.Port > math.MaxUint16 {
  323. return nil, common.NewErrorf("invalid port: %d", req.Port)
  324. }
  325. network := xnet.Network_TCP
  326. if strings.EqualFold(req.Network, "udp") {
  327. network = xnet.Network_UDP
  328. }
  329. rc := &routerService.RoutingContext{
  330. InboundTag: req.InboundTag,
  331. Network: network,
  332. TargetDomain: req.Domain,
  333. TargetPort: uint32(req.Port),
  334. Protocol: req.Protocol,
  335. User: req.Email,
  336. }
  337. if req.IP != "" {
  338. parsed := net.ParseIP(req.IP)
  339. if parsed == nil {
  340. return nil, common.NewErrorf("invalid IP address: %s", req.IP)
  341. }
  342. if v4 := parsed.To4(); v4 != nil {
  343. rc.TargetIPs = [][]byte{v4}
  344. } else {
  345. rc.TargetIPs = [][]byte{parsed.To16()}
  346. }
  347. }
  348. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  349. defer cancel()
  350. resp, err := (*x.RoutingServiceClient).TestRoute(ctx, &routerService.TestRouteRequest{
  351. RoutingContext: rc,
  352. PublishResult: false,
  353. })
  354. if err != nil {
  355. // The router reports "no rule matched" as an error; for the caller
  356. // that simply means the default outbound takes the traffic.
  357. if strings.Contains(strings.ToLower(err.Error()), "not enough information") {
  358. return &RouteTestResult{Matched: false}, nil
  359. }
  360. return nil, err
  361. }
  362. return &RouteTestResult{
  363. Matched: true,
  364. OutboundTag: resp.GetOutboundTag(),
  365. GroupTags: resp.GetOutboundGroupTags(),
  366. }, nil
  367. }
  368. // IsMissingHandlerErr reports whether err is xray's response to removing a
  369. // handler (inbound/outbound) that does not exist — e.g. it was already
  370. // removed through the runtime API while the panel's config snapshot was
  371. // stale. Safe to treat as success for removal operations.
  372. func IsMissingHandlerErr(err error) bool {
  373. if err == nil {
  374. return false
  375. }
  376. msg := strings.ToLower(err.Error())
  377. return strings.Contains(msg, "not found") ||
  378. strings.Contains(msg, "not enough information")
  379. }
  380. // IsExistingTagErr reports whether err is xray's response to adding a handler
  381. // whose tag is already taken by a running handler.
  382. func IsExistingTagErr(err error) bool {
  383. if err == nil {
  384. return false
  385. }
  386. return strings.Contains(strings.ToLower(err.Error()), "existing tag")
  387. }
  388. // IsUserExistsErr reports whether err is xray's response to adding a user whose
  389. // email is already registered on the inbound.
  390. func IsUserExistsErr(err error) bool {
  391. if err == nil {
  392. return false
  393. }
  394. return strings.Contains(strings.ToLower(err.Error()), "already exists")
  395. }
  396. // ensureXrayAssetLocation makes geoip.dat/geosite.dat resolvable when xray-core
  397. // config builders run inside the panel process. The xray binary resolves assets
  398. // relative to its own executable, but the panel binary lives one level above
  399. // the bin folder, so an explicit location is required.
  400. func ensureXrayAssetLocation() {
  401. if os.Getenv("XRAY_LOCATION_ASSET") != "" || os.Getenv("xray.location.asset") != "" {
  402. return
  403. }
  404. if abs, err := filepath.Abs(config.GetBinFolderPath()); err == nil {
  405. os.Setenv("XRAY_LOCATION_ASSET", abs)
  406. }
  407. }
  408. // collectStringSlice normalizes a JSON-decoded value into a slice of non-empty
  409. // strings, accepting both []string (typed maps) and []any (json.Unmarshal output).
  410. func collectStringSlice(value any) []string {
  411. switch v := value.(type) {
  412. case []string:
  413. out := make([]string, 0, len(v))
  414. for _, s := range v {
  415. if s != "" {
  416. out = append(out, s)
  417. }
  418. }
  419. return out
  420. case []any:
  421. out := make([]string, 0, len(v))
  422. for _, e := range v {
  423. if s, ok := e.(string); ok && s != "" {
  424. out = append(out, s)
  425. }
  426. }
  427. return out
  428. default:
  429. return nil
  430. }
  431. }
  432. // legacyShadowsocksAccountType is the type URL serial.ToTypedMessage stamps on
  433. // a pre-2022 shadowsocks account, which identifies the one inbound whose user
  434. // list tolerates duplicate emails.
  435. const legacyShadowsocksAccountType = "xray.proxy.shadowsocks.Account"
  436. // shadowsocks2022Ciphers are the methods that select xray's shadowsocks-2022
  437. // inbound (sing's shadowaead_2022 list). They take a different account type
  438. // than the legacy AEAD ciphers, and the running inbound casts the account it
  439. // receives without checking, so a wrong guess takes the whole core down.
  440. var shadowsocks2022Ciphers = map[string]struct{}{
  441. "2022-blake3-aes-128-gcm": {},
  442. "2022-blake3-aes-256-gcm": {},
  443. "2022-blake3-chacha20-poly1305": {},
  444. }
  445. // shadowsocksCipherName resolves the cipher a shadowsocks user's account must
  446. // be built for. Panel-built user maps carry it under "cipher"; client objects
  447. // taken verbatim from an inbound's settings carry the inbound's method under
  448. // "method" instead (HealShadowsocksClientMethods writes it onto every
  449. // legacy-cipher client).
  450. func shadowsocksCipherName(user map[string]any) (string, error) {
  451. cipher, err := getOptionalUserString(user, "cipher")
  452. if err != nil {
  453. return "", err
  454. }
  455. if cipher != "" {
  456. return cipher, nil
  457. }
  458. return getOptionalUserString(user, "method")
  459. }
  460. // reverseTag reads a vless reverse proxy tag from either shape a caller can
  461. // carry: the settings JSON object, or a typed client value marshalling alike.
  462. func reverseTag(value any) string {
  463. if value == nil {
  464. return ""
  465. }
  466. raw, err := json.Marshal(value)
  467. if err != nil {
  468. return ""
  469. }
  470. var parsed struct {
  471. Tag string `json:"tag"`
  472. }
  473. if json.Unmarshal(raw, &parsed) != nil {
  474. return ""
  475. }
  476. return parsed.Tag
  477. }
  478. // shadowsocksCipherType mirrors xray-core's infra/conf cipherFromString,
  479. // aliases and case-insensitivity included, so the account the panel builds for
  480. // a live user matches the one the core built for that inbound from its config.
  481. func shadowsocksCipherType(cipher string) shadowsocks.CipherType {
  482. switch strings.ToLower(cipher) {
  483. case "aes-128-gcm", "aead_aes_128_gcm":
  484. return shadowsocks.CipherType_AES_128_GCM
  485. case "aes-256-gcm", "aead_aes_256_gcm":
  486. return shadowsocks.CipherType_AES_256_GCM
  487. case "chacha20-poly1305", "aead_chacha20_poly1305", "chacha20-ietf-poly1305":
  488. return shadowsocks.CipherType_CHACHA20_POLY1305
  489. case "xchacha20-poly1305", "aead_xchacha20_poly1305", "xchacha20-ietf-poly1305":
  490. return shadowsocks.CipherType_XCHACHA20_POLY1305
  491. default:
  492. return shadowsocks.CipherType_UNKNOWN
  493. }
  494. }
  495. // isShadowsocks2022Cipher reports whether the method selects the
  496. // shadowsocks-2022 inbound rather than the legacy AEAD one.
  497. func isShadowsocks2022Cipher(cipher string) bool {
  498. _, ok := shadowsocks2022Ciphers[strings.ToLower(cipher)]
  499. return ok
  500. }
  501. // buildUserAccount constructs the typed xray account for a user of the given
  502. // protocol. It returns (nil, nil) for protocols that cannot be altered live so
  503. // callers skip the AlterInbound call. WireGuard keys must be converted to the
  504. // hex form xray's wireguard proxy expects (its ParseKey uses hex.DecodeString),
  505. // unlike the file-config path which accepts base64 and converts internally.
  506. // Shadowsocks is resolved strictly from the inbound's cipher: the legacy and
  507. // 2022 inbounds take different account types and cast whatever they receive
  508. // without checking, so an unrecognized cipher is an error rather than a guess
  509. // that would panic the core and kill every connection on the server.
  510. func buildUserAccount(protocolName string, user map[string]any) (*serial.TypedMessage, error) {
  511. switch protocolName {
  512. case "vmess":
  513. userID, err := getRequiredUserString(user, "id")
  514. if err != nil {
  515. return nil, err
  516. }
  517. return serial.ToTypedMessage(&vmess.Account{
  518. Id: userID,
  519. }), nil
  520. case "vless":
  521. userID, err := getRequiredUserString(user, "id")
  522. if err != nil {
  523. return nil, err
  524. }
  525. userFlow, err := getOptionalUserString(user, "flow")
  526. if err != nil {
  527. return nil, err
  528. }
  529. vlessAccount := &vless.Account{
  530. Id: userID,
  531. Flow: userFlow,
  532. }
  533. // RemoveUser also drops the account's reverse outbound handler, and
  534. // GetReverse only rebuilds it from the tag a re-added account carries.
  535. if tag := reverseTag(user["reverse"]); tag != "" {
  536. vlessAccount.Reverse = &vless.Reverse{Tag: tag}
  537. }
  538. if testseedVal, ok := user["testseed"]; ok {
  539. if testseedArr, ok := testseedVal.([]any); ok && len(testseedArr) >= 4 {
  540. testseed := make([]uint32, len(testseedArr))
  541. for i, v := range testseedArr {
  542. if num, ok := v.(float64); ok {
  543. testseed[i] = uint32(num)
  544. }
  545. }
  546. vlessAccount.Testseed = testseed
  547. } else if testseedArr, ok := testseedVal.([]uint32); ok && len(testseedArr) >= 4 {
  548. vlessAccount.Testseed = testseedArr
  549. }
  550. }
  551. if testpreVal, ok := user["testpre"]; ok {
  552. if testpre, ok := testpreVal.(float64); ok && testpre > 0 {
  553. vlessAccount.Testpre = uint32(testpre)
  554. } else if testpre, ok := testpreVal.(uint32); ok && testpre > 0 {
  555. vlessAccount.Testpre = testpre
  556. }
  557. }
  558. return serial.ToTypedMessage(vlessAccount), nil
  559. case "trojan":
  560. password, err := getRequiredUserString(user, "password")
  561. if err != nil {
  562. return nil, err
  563. }
  564. return serial.ToTypedMessage(&trojan.Account{
  565. Password: password,
  566. }), nil
  567. case "shadowsocks":
  568. cipher, err := shadowsocksCipherName(user)
  569. if err != nil {
  570. return nil, err
  571. }
  572. password, err := getRequiredUserString(user, "password")
  573. if err != nil {
  574. return nil, err
  575. }
  576. if isShadowsocks2022Cipher(cipher) {
  577. return serial.ToTypedMessage(&shadowsocks_2022.Account{
  578. Key: password,
  579. }), nil
  580. }
  581. ssCipherType := shadowsocksCipherType(cipher)
  582. if ssCipherType == shadowsocks.CipherType_UNKNOWN {
  583. return nil, common.NewErrorf("shadowsocks: unknown cipher %q, cannot build an account for the running inbound", cipher)
  584. }
  585. return serial.ToTypedMessage(&shadowsocks.Account{
  586. Password: password,
  587. CipherType: ssCipherType,
  588. }), nil
  589. case "hysteria":
  590. auth, err := getRequiredUserString(user, "auth")
  591. if err != nil {
  592. return nil, err
  593. }
  594. return serial.ToTypedMessage(&hysteriaAccount.Account{
  595. Auth: auth,
  596. }), nil
  597. case "wireguard":
  598. pubB64, err := getRequiredUserString(user, "publicKey")
  599. if err != nil {
  600. return nil, err
  601. }
  602. pubHex, err := wgutil.KeyToHex(pubB64)
  603. if err != nil {
  604. return nil, fmt.Errorf("wireguard publicKey: %w", err)
  605. }
  606. pskB64, err := getOptionalUserString(user, "preSharedKey")
  607. if err != nil {
  608. return nil, err
  609. }
  610. pskHex, err := wgutil.KeyToHex(pskB64)
  611. if err != nil {
  612. return nil, fmt.Errorf("wireguard preSharedKey: %w", err)
  613. }
  614. allowed := collectStringSlice(user["allowedIPs"])
  615. if len(allowed) == 0 {
  616. return nil, common.NewError("wireguard: allowedIPs required")
  617. }
  618. keepAlive, err := getOptionalUserString(user, "keepAlive")
  619. if err != nil {
  620. return nil, err
  621. }
  622. return serial.ToTypedMessage(&wireguard.PeerConfig{
  623. PublicKey: pubHex,
  624. PreSharedKey: pskHex,
  625. AllowedIps: allowed,
  626. KeepAlive: keepAlive,
  627. }), nil
  628. default:
  629. return nil, nil
  630. }
  631. }
  632. // AddUser adds a user to an inbound in the Xray core using the specified
  633. // protocol and user data. On a legacy shadowsocks inbound the add first drops
  634. // any existing holder of the email: that is the one inbound whose validator
  635. // does not reject a duplicate email, and a later removal would then drop just
  636. // one of the two registrations, leaving a disabled client able to connect.
  637. func (x *XrayAPI) AddUser(Protocol string, inboundTag string, user map[string]any) error {
  638. userEmail, err := getRequiredUserString(user, "email")
  639. if err != nil {
  640. return err
  641. }
  642. account, err := buildUserAccount(Protocol, user)
  643. if err != nil {
  644. return err
  645. }
  646. if account == nil {
  647. return nil
  648. }
  649. if x.HandlerServiceClient == nil {
  650. return common.NewError("xray HandlerServiceClient is not initialized")
  651. }
  652. client := *x.HandlerServiceClient
  653. if account.Type == legacyShadowsocksAccountType {
  654. _ = x.RemoveUser(inboundTag, userEmail)
  655. }
  656. ctx, cancel := context.WithTimeout(context.Background(), handlerRPCTimeout)
  657. defer cancel()
  658. _, err = client.AlterInbound(ctx, &command.AlterInboundRequest{
  659. Tag: inboundTag,
  660. Operation: serial.ToTypedMessage(&command.AddUserOperation{
  661. User: &protocol.User{
  662. Email: userEmail,
  663. Account: account,
  664. },
  665. }),
  666. })
  667. return err
  668. }
  669. // RemoveUser removes a user from an inbound in the Xray core by email.
  670. func (x *XrayAPI) RemoveUser(inboundTag, email string) error {
  671. if x.HandlerServiceClient == nil {
  672. return common.NewError("xray HandlerServiceClient is not initialized")
  673. }
  674. client := *x.HandlerServiceClient
  675. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  676. defer cancel()
  677. op := &command.RemoveUserOperation{Email: email}
  678. req := &command.AlterInboundRequest{
  679. Tag: inboundTag,
  680. Operation: serial.ToTypedMessage(op),
  681. }
  682. _, err := client.AlterInbound(ctx, req)
  683. if err != nil {
  684. return fmt.Errorf("failed to remove user: %w", err)
  685. }
  686. return nil
  687. }
  688. // GetTraffic queries traffic statistics from the Xray core and reports what
  689. // accrued since the previous call; the counters themselves are never reset.
  690. // The first call of a process only records baselines, since it may be reading
  691. // counters that already hold traffic the panel cannot attribute. After that a
  692. // name the panel has not seen — xray creates a counter on a user's first use —
  693. // and a counter that moved backwards because the core restarted both count
  694. // from zero, so no client's traffic is dropped for a whole polling interval.
  695. func (x *XrayAPI) GetTraffic() ([]*Traffic, []*ClientTraffic, error) {
  696. if x.grpcClient == nil {
  697. return nil, nil, common.NewError("xray api is not initialized")
  698. }
  699. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  700. defer cancel()
  701. if x.StatsServiceClient == nil {
  702. return nil, nil, common.NewError("xray StatusServiceClient is not initialized")
  703. }
  704. resp, err := (*x.StatsServiceClient).QueryStats(ctx, &statsService.QueryStatsRequest{Reset_: false})
  705. if err != nil {
  706. logger.Debug("Failed to query Xray stats:", err)
  707. return nil, nil, err
  708. }
  709. tagTrafficMap := make(map[string]*Traffic)
  710. emailTrafficMap := make(map[string]*ClientTraffic)
  711. baselinePass := len(x.StatsLastValues) == 0
  712. for _, stat := range resp.GetStat() {
  713. lastValue, ok := x.StatsLastValues[stat.Name]
  714. x.StatsLastValues[stat.Name] = stat.Value
  715. if baselinePass {
  716. continue
  717. }
  718. if !ok || stat.Value < lastValue {
  719. lastValue = 0
  720. }
  721. value := stat.Value - lastValue
  722. if matches := trafficRegex.FindStringSubmatch(stat.Name); len(matches) == 4 {
  723. processTraffic(matches, value, tagTrafficMap)
  724. } else if matches := clientTrafficRegex.FindStringSubmatch(stat.Name); len(matches) == 3 {
  725. processClientTraffic(matches, value, emailTrafficMap)
  726. }
  727. }
  728. // Drop delta baselines for stats that no longer exist (deleted inbounds or
  729. // clients), which otherwise linger until the next Xray restart. Only rebuild
  730. // when the map has drifted past 2x the live set, so the steady-state hot path
  731. // stays allocation-free.
  732. if n := len(resp.GetStat()); n > 0 && len(x.StatsLastValues) > 2*n {
  733. pruned := make(map[string]int64, n)
  734. for _, stat := range resp.GetStat() {
  735. pruned[stat.Name] = x.StatsLastValues[stat.Name]
  736. }
  737. x.StatsLastValues = pruned
  738. }
  739. return mapToSlice(tagTrafficMap), mapToSlice(emailTrafficMap), nil
  740. }
  741. // OnlineIP is one source address of a live connection, with the unix time (seconds)
  742. // the core last dispatched a link from it.
  743. type OnlineIP struct {
  744. IP string `json:"ip"`
  745. LastSeen int64 `json:"lastSeen"`
  746. }
  747. // OnlineUser is a client email with at least one live connection and the source
  748. // IPs of those connections, as tracked by Xray's statsUserOnline policy.
  749. type OnlineUser struct {
  750. Email string `json:"email"`
  751. IPs []OnlineIP `json:"ips"`
  752. }
  753. // GetOnlineUsers returns every user with at least one live connection plus their
  754. // source IPs, via StatsService.GetUsersStats (one RPC covers all users). Requires
  755. // statsUserOnline enabled in the policy levels; older cores return Unimplemented.
  756. func (x *XrayAPI) GetOnlineUsers() ([]OnlineUser, error) {
  757. if x.grpcClient == nil {
  758. return nil, common.NewError("xray api is not initialized")
  759. }
  760. if x.StatsServiceClient == nil {
  761. return nil, common.NewError("xray StatsServiceClient is not initialized")
  762. }
  763. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  764. defer cancel()
  765. resp, err := (*x.StatsServiceClient).GetUsersStats(ctx, &statsService.GetUsersStatsRequest{})
  766. if err != nil {
  767. return nil, err
  768. }
  769. users := make([]OnlineUser, 0, len(resp.GetUsers()))
  770. for _, u := range resp.GetUsers() {
  771. if u == nil || u.GetEmail() == "" {
  772. continue
  773. }
  774. ips := make([]OnlineIP, 0, len(u.GetIps()))
  775. for _, entry := range u.GetIps() {
  776. if entry == nil || entry.GetIp() == "" {
  777. continue
  778. }
  779. ips = append(ips, OnlineIP{IP: entry.GetIp(), LastSeen: entry.GetLastSeen()})
  780. }
  781. users = append(users, OnlineUser{Email: u.GetEmail(), IPs: ips})
  782. }
  783. return users, nil
  784. }
  785. // IsUnimplementedErr reports whether err is the running core saying it lacks an
  786. // RPC (an older Xray binary without the online-stats API).
  787. func IsUnimplementedErr(err error) bool {
  788. return status.Code(err) == codes.Unimplemented
  789. }
  790. // processTraffic aggregates a traffic stat into trafficMap using regex matches and value.
  791. func processTraffic(matches []string, value int64, trafficMap map[string]*Traffic) {
  792. isInbound := matches[1] == "inbound"
  793. tag := matches[2]
  794. isDown := matches[3] == "downlink"
  795. if tag == "api" {
  796. return
  797. }
  798. traffic, ok := trafficMap[tag]
  799. if !ok {
  800. traffic = &Traffic{
  801. IsInbound: isInbound,
  802. IsOutbound: !isInbound,
  803. Tag: tag,
  804. }
  805. trafficMap[tag] = traffic
  806. }
  807. if isDown {
  808. traffic.Down = value
  809. } else {
  810. traffic.Up = value
  811. }
  812. }
  813. // processClientTraffic updates clientTrafficMap with upload/download values for a client email.
  814. func processClientTraffic(matches []string, value int64, clientTrafficMap map[string]*ClientTraffic) {
  815. email := matches[1]
  816. isDown := matches[2] == "downlink"
  817. traffic, ok := clientTrafficMap[email]
  818. if !ok {
  819. traffic = &ClientTraffic{Email: email}
  820. clientTrafficMap[email] = traffic
  821. }
  822. if isDown {
  823. traffic.Down = value
  824. } else {
  825. traffic.Up = value
  826. }
  827. }
  828. // mapToSlice converts a map of pointers to a slice of pointers.
  829. func mapToSlice[T any](m map[string]*T) []*T {
  830. result := make([]*T, 0, len(m))
  831. for _, v := range m {
  832. result = append(result, v)
  833. }
  834. return result
  835. }