api.go 30 KB

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