1
0

api.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. // Package xray provides integration with the Xray proxy core.
  2. // It includes API client functionality, configuration management, traffic monitoring,
  3. // and process control for Xray instances.
  4. package xray
  5. import (
  6. "context"
  7. "encoding/json"
  8. "fmt"
  9. "math"
  10. "net"
  11. "os"
  12. "path/filepath"
  13. "regexp"
  14. "strings"
  15. "time"
  16. "github.com/mhsanaei/3x-ui/v3/internal/config"
  17. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  18. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  19. "github.com/xtls/xray-core/app/proxyman/command"
  20. routerService "github.com/xtls/xray-core/app/router/command"
  21. statsService "github.com/xtls/xray-core/app/stats/command"
  22. xnet "github.com/xtls/xray-core/common/net"
  23. "github.com/xtls/xray-core/common/protocol"
  24. "github.com/xtls/xray-core/common/serial"
  25. "github.com/xtls/xray-core/infra/conf"
  26. hysteriaAccount "github.com/xtls/xray-core/proxy/hysteria/account"
  27. "github.com/xtls/xray-core/proxy/shadowsocks"
  28. "github.com/xtls/xray-core/proxy/shadowsocks_2022"
  29. "github.com/xtls/xray-core/proxy/trojan"
  30. "github.com/xtls/xray-core/proxy/vless"
  31. "github.com/xtls/xray-core/proxy/vmess"
  32. "google.golang.org/grpc"
  33. "google.golang.org/grpc/credentials/insecure"
  34. )
  35. // XrayAPI is a gRPC client for managing Xray core configuration, inbounds, outbounds, and statistics.
  36. type XrayAPI struct {
  37. HandlerServiceClient *command.HandlerServiceClient
  38. StatsServiceClient *statsService.StatsServiceClient
  39. RoutingServiceClient *routerService.RoutingServiceClient
  40. grpcClient *grpc.ClientConn
  41. isConnected bool
  42. StatsLastValues map[string]int64
  43. }
  44. func getRequiredUserString(user map[string]any, key string) (string, error) {
  45. value, ok := user[key]
  46. if !ok || value == nil {
  47. return "", fmt.Errorf("missing required user field %q", key)
  48. }
  49. strValue, ok := value.(string)
  50. if !ok {
  51. return "", fmt.Errorf("invalid type for user field %q: %T", key, value)
  52. }
  53. return strValue, nil
  54. }
  55. func getOptionalUserString(user map[string]any, key string) (string, error) {
  56. value, ok := user[key]
  57. if !ok || value == nil {
  58. return "", nil
  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. // Init connects to the Xray API server and initializes handler and stats service clients.
  67. func (x *XrayAPI) Init(apiPort int) error {
  68. if apiPort <= 0 || apiPort > math.MaxUint16 {
  69. return fmt.Errorf("invalid Xray API port: %d", apiPort)
  70. }
  71. addr := fmt.Sprintf("127.0.0.1:%d", apiPort)
  72. conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
  73. if err != nil {
  74. return fmt.Errorf("failed to connect to Xray API: %w", err)
  75. }
  76. x.grpcClient = conn
  77. x.isConnected = true
  78. if x.StatsLastValues == nil {
  79. x.StatsLastValues = make(map[string]int64)
  80. }
  81. hsClient := command.NewHandlerServiceClient(conn)
  82. ssClient := statsService.NewStatsServiceClient(conn)
  83. rsClient := routerService.NewRoutingServiceClient(conn)
  84. x.HandlerServiceClient = &hsClient
  85. x.StatsServiceClient = &ssClient
  86. x.RoutingServiceClient = &rsClient
  87. return nil
  88. }
  89. // Close closes the gRPC connection and resets the XrayAPI client state.
  90. func (x *XrayAPI) Close() {
  91. if x.grpcClient != nil {
  92. x.grpcClient.Close()
  93. }
  94. x.HandlerServiceClient = nil
  95. x.StatsServiceClient = nil
  96. x.RoutingServiceClient = nil
  97. x.isConnected = false
  98. }
  99. // AddInbound adds a new inbound configuration to the Xray core via gRPC.
  100. func (x *XrayAPI) AddInbound(inbound []byte) error {
  101. client := *x.HandlerServiceClient
  102. conf := new(conf.InboundDetourConfig)
  103. err := json.Unmarshal(inbound, conf)
  104. if err != nil {
  105. logger.Debug("Failed to unmarshal inbound:", err)
  106. return err
  107. }
  108. config, err := conf.Build()
  109. if err != nil {
  110. logger.Debug("Failed to build inbound Detur:", err)
  111. return err
  112. }
  113. inboundConfig := command.AddInboundRequest{Inbound: config}
  114. _, err = client.AddInbound(context.Background(), &inboundConfig)
  115. return err
  116. }
  117. // DelInbound removes an inbound configuration from the Xray core by tag.
  118. func (x *XrayAPI) DelInbound(tag string) error {
  119. client := *x.HandlerServiceClient
  120. _, err := client.RemoveInbound(context.Background(), &command.RemoveInboundRequest{
  121. Tag: tag,
  122. })
  123. return err
  124. }
  125. // AddOutbound adds a new outbound configuration to the Xray core via gRPC.
  126. func (x *XrayAPI) AddOutbound(outbound []byte) error {
  127. if x.HandlerServiceClient == nil {
  128. return common.NewError("xray HandlerServiceClient is not initialized")
  129. }
  130. client := *x.HandlerServiceClient
  131. conf := new(conf.OutboundDetourConfig)
  132. if err := json.Unmarshal(outbound, conf); err != nil {
  133. logger.Debug("Failed to unmarshal outbound:", err)
  134. return err
  135. }
  136. config, err := conf.Build()
  137. if err != nil {
  138. logger.Debug("Failed to build outbound detour:", err)
  139. return err
  140. }
  141. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  142. defer cancel()
  143. _, err = client.AddOutbound(ctx, &command.AddOutboundRequest{Outbound: config})
  144. return err
  145. }
  146. // DelOutbound removes an outbound configuration from the Xray core by tag.
  147. func (x *XrayAPI) DelOutbound(tag string) error {
  148. if x.HandlerServiceClient == nil {
  149. return common.NewError("xray HandlerServiceClient is not initialized")
  150. }
  151. client := *x.HandlerServiceClient
  152. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  153. defer cancel()
  154. _, err := client.RemoveOutbound(ctx, &command.RemoveOutboundRequest{Tag: tag})
  155. return err
  156. }
  157. // ApplyRoutingConfig replaces the routing rules and balancers of the running
  158. // Xray core with the given routing section (the JSON value of the top-level
  159. // "routing" key) via the RoutingService gRPC API. Note that this cannot change
  160. // routing.domainStrategy/domainMatcher — those are fixed at process start.
  161. func (x *XrayAPI) ApplyRoutingConfig(routing []byte) error {
  162. if x.RoutingServiceClient == nil {
  163. return common.NewError("xray RoutingServiceClient is not initialized")
  164. }
  165. // Rules referencing geoip:/geosite: need the dat files; point xray-core's
  166. // in-process loader at the panel's bin folder where they live.
  167. ensureXrayAssetLocation()
  168. routerConf := new(conf.RouterConfig)
  169. if err := json.Unmarshal(routing, routerConf); err != nil {
  170. logger.Debug("Failed to unmarshal routing config:", err)
  171. return err
  172. }
  173. config, err := routerConf.Build()
  174. if err != nil {
  175. logger.Debug("Failed to build routing config:", err)
  176. return err
  177. }
  178. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  179. defer cancel()
  180. _, err = (*x.RoutingServiceClient).AddRule(ctx, &routerService.AddRuleRequest{
  181. ShouldAppend: false,
  182. Config: serial.ToTypedMessage(config),
  183. })
  184. return err
  185. }
  186. // BalancerInfo is the live state of one balancer inside the running core.
  187. type BalancerInfo struct {
  188. Tag string `json:"tag"`
  189. // Override is the outbound tag an admin forced via the API; empty when
  190. // the strategy is in control.
  191. Override string `json:"override"`
  192. // Selected are the outbound tags the strategy currently prefers, best
  193. // first (xray's "principle target" list).
  194. Selected []string `json:"selected"`
  195. }
  196. // GetBalancerInfo queries the running core for a balancer's current override
  197. // and the targets its strategy would pick right now.
  198. func (x *XrayAPI) GetBalancerInfo(tag string) (*BalancerInfo, error) {
  199. if x.RoutingServiceClient == nil {
  200. return nil, common.NewError("xray RoutingServiceClient is not initialized")
  201. }
  202. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  203. defer cancel()
  204. resp, err := (*x.RoutingServiceClient).GetBalancerInfo(ctx, &routerService.GetBalancerInfoRequest{Tag: tag})
  205. if err != nil {
  206. return nil, err
  207. }
  208. info := &BalancerInfo{Tag: tag}
  209. if balancer := resp.GetBalancer(); balancer != nil {
  210. if balancer.Override != nil {
  211. info.Override = balancer.Override.Target
  212. }
  213. if balancer.PrincipleTarget != nil {
  214. info.Selected = balancer.PrincipleTarget.Tag
  215. }
  216. }
  217. return info, nil
  218. }
  219. // SetBalancerTarget forces a balancer to always pick the given outbound tag.
  220. // An empty target clears the override and hands control back to the strategy.
  221. func (x *XrayAPI) SetBalancerTarget(tag, target string) error {
  222. if x.RoutingServiceClient == nil {
  223. return common.NewError("xray RoutingServiceClient is not initialized")
  224. }
  225. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  226. defer cancel()
  227. _, err := (*x.RoutingServiceClient).OverrideBalancerTarget(ctx, &routerService.OverrideBalancerTargetRequest{
  228. BalancerTag: tag,
  229. Target: target,
  230. })
  231. return err
  232. }
  233. // RouteTestRequest describes a synthetic connection to ask the running core
  234. // which outbound its router would pick for it.
  235. type RouteTestRequest struct {
  236. InboundTag string // optional: simulate arrival on this inbound
  237. Domain string // target domain (sniffed/SOCKS-style destination)
  238. IP string // target IP, used when Domain is empty or alongside it
  239. Port int
  240. Network string // "tcp" (default) or "udp"
  241. Protocol string // optional sniffed protocol: http, tls, bittorrent, ...
  242. Email string // optional user attribution for user-based rules
  243. }
  244. // RouteTestResult is the routing decision the core reported.
  245. type RouteTestResult struct {
  246. // Matched is false when no routing rule matched — traffic would use the
  247. // default (first) outbound and OutboundTag is empty.
  248. Matched bool `json:"matched"`
  249. OutboundTag string `json:"outboundTag"`
  250. // GroupTags lists the balancer chain the decision went through, when any.
  251. GroupTags []string `json:"groupTags,omitempty"`
  252. }
  253. // TestRoute asks the running core's router which outbound it would pick for
  254. // the described connection, without sending any traffic.
  255. func (x *XrayAPI) TestRoute(req RouteTestRequest) (*RouteTestResult, error) {
  256. if x.RoutingServiceClient == nil {
  257. return nil, common.NewError("xray RoutingServiceClient is not initialized")
  258. }
  259. network := xnet.Network_TCP
  260. if strings.EqualFold(req.Network, "udp") {
  261. network = xnet.Network_UDP
  262. }
  263. rc := &routerService.RoutingContext{
  264. InboundTag: req.InboundTag,
  265. Network: network,
  266. TargetDomain: req.Domain,
  267. TargetPort: uint32(req.Port),
  268. Protocol: req.Protocol,
  269. User: req.Email,
  270. }
  271. if req.IP != "" {
  272. parsed := net.ParseIP(req.IP)
  273. if parsed == nil {
  274. return nil, common.NewErrorf("invalid IP address: %s", req.IP)
  275. }
  276. if v4 := parsed.To4(); v4 != nil {
  277. rc.TargetIPs = [][]byte{v4}
  278. } else {
  279. rc.TargetIPs = [][]byte{parsed.To16()}
  280. }
  281. }
  282. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  283. defer cancel()
  284. resp, err := (*x.RoutingServiceClient).TestRoute(ctx, &routerService.TestRouteRequest{
  285. RoutingContext: rc,
  286. PublishResult: false,
  287. })
  288. if err != nil {
  289. // The router reports "no rule matched" as an error; for the caller
  290. // that simply means the default outbound takes the traffic.
  291. if strings.Contains(strings.ToLower(err.Error()), "not enough information") {
  292. return &RouteTestResult{Matched: false}, nil
  293. }
  294. return nil, err
  295. }
  296. return &RouteTestResult{
  297. Matched: true,
  298. OutboundTag: resp.GetOutboundTag(),
  299. GroupTags: resp.GetOutboundGroupTags(),
  300. }, nil
  301. }
  302. // IsMissingHandlerErr reports whether err is xray's response to removing a
  303. // handler (inbound/outbound) that does not exist — e.g. it was already
  304. // removed through the runtime API while the panel's config snapshot was
  305. // stale. Safe to treat as success for removal operations.
  306. func IsMissingHandlerErr(err error) bool {
  307. if err == nil {
  308. return false
  309. }
  310. msg := strings.ToLower(err.Error())
  311. return strings.Contains(msg, "not found") ||
  312. strings.Contains(msg, "not enough information")
  313. }
  314. // IsExistingTagErr reports whether err is xray's response to adding a handler
  315. // whose tag is already taken by a running handler.
  316. func IsExistingTagErr(err error) bool {
  317. if err == nil {
  318. return false
  319. }
  320. return strings.Contains(strings.ToLower(err.Error()), "existing tag")
  321. }
  322. // ensureXrayAssetLocation makes geoip.dat/geosite.dat resolvable when xray-core
  323. // config builders run inside the panel process. The xray binary resolves assets
  324. // relative to its own executable, but the panel binary lives one level above
  325. // the bin folder, so an explicit location is required.
  326. func ensureXrayAssetLocation() {
  327. if os.Getenv("XRAY_LOCATION_ASSET") != "" || os.Getenv("xray.location.asset") != "" {
  328. return
  329. }
  330. if abs, err := filepath.Abs(config.GetBinFolderPath()); err == nil {
  331. os.Setenv("XRAY_LOCATION_ASSET", abs)
  332. }
  333. }
  334. // AddUser adds a user to an inbound in the Xray core using the specified protocol and user data.
  335. func (x *XrayAPI) AddUser(Protocol string, inboundTag string, user map[string]any) error {
  336. userEmail, err := getRequiredUserString(user, "email")
  337. if err != nil {
  338. return err
  339. }
  340. var account *serial.TypedMessage
  341. switch Protocol {
  342. case "vmess":
  343. userID, err := getRequiredUserString(user, "id")
  344. if err != nil {
  345. return err
  346. }
  347. account = serial.ToTypedMessage(&vmess.Account{
  348. Id: userID,
  349. })
  350. case "vless":
  351. userID, err := getRequiredUserString(user, "id")
  352. if err != nil {
  353. return err
  354. }
  355. userFlow, err := getOptionalUserString(user, "flow")
  356. if err != nil {
  357. return err
  358. }
  359. vlessAccount := &vless.Account{
  360. Id: userID,
  361. Flow: userFlow,
  362. }
  363. // Add testseed if provided
  364. if testseedVal, ok := user["testseed"]; ok {
  365. if testseedArr, ok := testseedVal.([]any); ok && len(testseedArr) >= 4 {
  366. testseed := make([]uint32, len(testseedArr))
  367. for i, v := range testseedArr {
  368. if num, ok := v.(float64); ok {
  369. testseed[i] = uint32(num)
  370. }
  371. }
  372. vlessAccount.Testseed = testseed
  373. } else if testseedArr, ok := testseedVal.([]uint32); ok && len(testseedArr) >= 4 {
  374. vlessAccount.Testseed = testseedArr
  375. }
  376. }
  377. // Add testpre if provided (for outbound, but can be in user for compatibility)
  378. if testpreVal, ok := user["testpre"]; ok {
  379. if testpre, ok := testpreVal.(float64); ok && testpre > 0 {
  380. vlessAccount.Testpre = uint32(testpre)
  381. } else if testpre, ok := testpreVal.(uint32); ok && testpre > 0 {
  382. vlessAccount.Testpre = testpre
  383. }
  384. }
  385. account = serial.ToTypedMessage(vlessAccount)
  386. case "trojan":
  387. password, err := getRequiredUserString(user, "password")
  388. if err != nil {
  389. return err
  390. }
  391. account = serial.ToTypedMessage(&trojan.Account{
  392. Password: password,
  393. })
  394. case "shadowsocks":
  395. cipher, err := getOptionalUserString(user, "cipher")
  396. if err != nil {
  397. return err
  398. }
  399. password, err := getRequiredUserString(user, "password")
  400. if err != nil {
  401. return err
  402. }
  403. var ssCipherType shadowsocks.CipherType
  404. switch cipher {
  405. case "aes-256-gcm":
  406. ssCipherType = shadowsocks.CipherType_AES_256_GCM
  407. case "chacha20-poly1305", "chacha20-ietf-poly1305":
  408. ssCipherType = shadowsocks.CipherType_CHACHA20_POLY1305
  409. case "xchacha20-poly1305", "xchacha20-ietf-poly1305":
  410. ssCipherType = shadowsocks.CipherType_XCHACHA20_POLY1305
  411. default:
  412. ssCipherType = shadowsocks.CipherType_NONE
  413. }
  414. if ssCipherType != shadowsocks.CipherType_NONE {
  415. account = serial.ToTypedMessage(&shadowsocks.Account{
  416. Password: password,
  417. CipherType: ssCipherType,
  418. })
  419. } else {
  420. account = serial.ToTypedMessage(&shadowsocks_2022.ServerConfig{
  421. Key: password,
  422. Email: userEmail,
  423. })
  424. }
  425. case "hysteria":
  426. auth, err := getRequiredUserString(user, "auth")
  427. if err != nil {
  428. return err
  429. }
  430. account = serial.ToTypedMessage(&hysteriaAccount.Account{
  431. Auth: auth,
  432. })
  433. default:
  434. return nil
  435. }
  436. client := *x.HandlerServiceClient
  437. _, err = client.AlterInbound(context.Background(), &command.AlterInboundRequest{
  438. Tag: inboundTag,
  439. Operation: serial.ToTypedMessage(&command.AddUserOperation{
  440. User: &protocol.User{
  441. Email: userEmail,
  442. Account: account,
  443. },
  444. }),
  445. })
  446. return err
  447. }
  448. // RemoveUser removes a user from an inbound in the Xray core by email.
  449. func (x *XrayAPI) RemoveUser(inboundTag, email string) error {
  450. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  451. defer cancel()
  452. op := &command.RemoveUserOperation{Email: email}
  453. req := &command.AlterInboundRequest{
  454. Tag: inboundTag,
  455. Operation: serial.ToTypedMessage(op),
  456. }
  457. _, err := (*x.HandlerServiceClient).AlterInbound(ctx, req)
  458. if err != nil {
  459. return fmt.Errorf("failed to remove user: %w", err)
  460. }
  461. return nil
  462. }
  463. // GetTraffic queries traffic statistics from the Xray core, optionally resetting counters.
  464. func (x *XrayAPI) GetTraffic() ([]*Traffic, []*ClientTraffic, error) {
  465. if x.grpcClient == nil {
  466. return nil, nil, common.NewError("xray api is not initialized")
  467. }
  468. trafficRegex := regexp.MustCompile(`(inbound|outbound)>>>([^>]+)>>>traffic>>>(downlink|uplink)`)
  469. clientTrafficRegex := regexp.MustCompile(`user>>>([^>]+)>>>traffic>>>(downlink|uplink)`)
  470. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  471. defer cancel()
  472. if x.StatsServiceClient == nil {
  473. return nil, nil, common.NewError("xray StatusServiceClient is not initialized")
  474. }
  475. resp, err := (*x.StatsServiceClient).QueryStats(ctx, &statsService.QueryStatsRequest{Reset_: false})
  476. if err != nil {
  477. logger.Debug("Failed to query Xray stats:", err)
  478. return nil, nil, err
  479. }
  480. tagTrafficMap := make(map[string]*Traffic)
  481. emailTrafficMap := make(map[string]*ClientTraffic)
  482. for _, stat := range resp.GetStat() {
  483. lastValue, ok := x.StatsLastValues[stat.Name]
  484. x.StatsLastValues[stat.Name] = stat.Value
  485. if !ok || stat.Value < lastValue {
  486. // skip first time of seen stat
  487. continue
  488. }
  489. value := stat.Value - lastValue
  490. if matches := trafficRegex.FindStringSubmatch(stat.Name); len(matches) == 4 {
  491. processTraffic(matches, value, tagTrafficMap)
  492. } else if matches := clientTrafficRegex.FindStringSubmatch(stat.Name); len(matches) == 3 {
  493. processClientTraffic(matches, value, emailTrafficMap)
  494. }
  495. }
  496. return mapToSlice(tagTrafficMap), mapToSlice(emailTrafficMap), nil
  497. }
  498. // processTraffic aggregates a traffic stat into trafficMap using regex matches and value.
  499. func processTraffic(matches []string, value int64, trafficMap map[string]*Traffic) {
  500. isInbound := matches[1] == "inbound"
  501. tag := matches[2]
  502. isDown := matches[3] == "downlink"
  503. if tag == "api" {
  504. return
  505. }
  506. traffic, ok := trafficMap[tag]
  507. if !ok {
  508. traffic = &Traffic{
  509. IsInbound: isInbound,
  510. IsOutbound: !isInbound,
  511. Tag: tag,
  512. }
  513. trafficMap[tag] = traffic
  514. }
  515. if isDown {
  516. traffic.Down = value
  517. } else {
  518. traffic.Up = value
  519. }
  520. }
  521. // processClientTraffic updates clientTrafficMap with upload/download values for a client email.
  522. func processClientTraffic(matches []string, value int64, clientTrafficMap map[string]*ClientTraffic) {
  523. email := matches[1]
  524. isDown := matches[2] == "downlink"
  525. traffic, ok := clientTrafficMap[email]
  526. if !ok {
  527. traffic = &ClientTraffic{Email: email}
  528. clientTrafficMap[email] = traffic
  529. }
  530. if isDown {
  531. traffic.Down = value
  532. } else {
  533. traffic.Up = value
  534. }
  535. }
  536. // mapToSlice converts a map of pointers to a slice of pointers.
  537. func mapToSlice[T any](m map[string]*T) []*T {
  538. result := make([]*T, 0, len(m))
  539. for _, v := range m {
  540. result = append(result, v)
  541. }
  542. return result
  543. }