api.go 31 KB

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