1
0

api.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. package xray
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "regexp"
  7. "time"
  8. "math"
  9. "x-ui/logger"
  10. "x-ui/util/common"
  11. "github.com/xtls/xray-core/app/proxyman/command"
  12. statsService "github.com/xtls/xray-core/app/stats/command"
  13. "github.com/xtls/xray-core/common/protocol"
  14. "github.com/xtls/xray-core/common/serial"
  15. "github.com/xtls/xray-core/infra/conf"
  16. "github.com/xtls/xray-core/proxy/shadowsocks"
  17. "github.com/xtls/xray-core/proxy/shadowsocks_2022"
  18. "github.com/xtls/xray-core/proxy/trojan"
  19. "github.com/xtls/xray-core/proxy/vless"
  20. "github.com/xtls/xray-core/proxy/vmess"
  21. "google.golang.org/grpc"
  22. "google.golang.org/grpc/credentials/insecure"
  23. )
  24. type XrayAPI struct {
  25. HandlerServiceClient *command.HandlerServiceClient
  26. StatsServiceClient *statsService.StatsServiceClient
  27. grpcClient *grpc.ClientConn
  28. isConnected bool
  29. }
  30. func (x *XrayAPI) Init(apiPort int) error {
  31. if apiPort <= 0 || apiPort > math.MaxUint16 {
  32. return fmt.Errorf("invalid Xray API port: %d", apiPort)
  33. }
  34. addr := fmt.Sprintf("127.0.0.1:%d", apiPort)
  35. conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
  36. if err != nil {
  37. return fmt.Errorf("failed to connect to Xray API: %w", err)
  38. }
  39. x.grpcClient = conn
  40. x.isConnected = true
  41. hsClient := command.NewHandlerServiceClient(conn)
  42. ssClient := statsService.NewStatsServiceClient(conn)
  43. x.HandlerServiceClient = &hsClient
  44. x.StatsServiceClient = &ssClient
  45. return nil
  46. }
  47. func (x *XrayAPI) Close() {
  48. if x.grpcClient != nil {
  49. x.grpcClient.Close()
  50. }
  51. x.HandlerServiceClient = nil
  52. x.StatsServiceClient = nil
  53. x.isConnected = false
  54. }
  55. func (x *XrayAPI) AddInbound(inbound []byte) error {
  56. client := *x.HandlerServiceClient
  57. conf := new(conf.InboundDetourConfig)
  58. err := json.Unmarshal(inbound, conf)
  59. if err != nil {
  60. logger.Debug("Failed to unmarshal inbound:", err)
  61. return err
  62. }
  63. config, err := conf.Build()
  64. if err != nil {
  65. logger.Debug("Failed to build inbound Detur:", err)
  66. return err
  67. }
  68. inboundConfig := command.AddInboundRequest{Inbound: config}
  69. _, err = client.AddInbound(context.Background(), &inboundConfig)
  70. return err
  71. }
  72. func (x *XrayAPI) DelInbound(tag string) error {
  73. client := *x.HandlerServiceClient
  74. _, err := client.RemoveInbound(context.Background(), &command.RemoveInboundRequest{
  75. Tag: tag,
  76. })
  77. return err
  78. }
  79. func (x *XrayAPI) AddUser(Protocol string, inboundTag string, user map[string]any) error {
  80. var account *serial.TypedMessage
  81. switch Protocol {
  82. case "vmess":
  83. account = serial.ToTypedMessage(&vmess.Account{
  84. Id: user["id"].(string),
  85. })
  86. case "vless":
  87. account = serial.ToTypedMessage(&vless.Account{
  88. Id: user["id"].(string),
  89. Flow: user["flow"].(string),
  90. })
  91. case "trojan":
  92. account = serial.ToTypedMessage(&trojan.Account{
  93. Password: user["password"].(string),
  94. })
  95. case "shadowsocks":
  96. var ssCipherType shadowsocks.CipherType
  97. switch user["cipher"].(string) {
  98. case "aes-128-gcm":
  99. ssCipherType = shadowsocks.CipherType_AES_128_GCM
  100. case "aes-256-gcm":
  101. ssCipherType = shadowsocks.CipherType_AES_256_GCM
  102. case "chacha20-poly1305", "chacha20-ietf-poly1305":
  103. ssCipherType = shadowsocks.CipherType_CHACHA20_POLY1305
  104. case "xchacha20-poly1305", "xchacha20-ietf-poly1305":
  105. ssCipherType = shadowsocks.CipherType_XCHACHA20_POLY1305
  106. default:
  107. ssCipherType = shadowsocks.CipherType_NONE
  108. }
  109. if ssCipherType != shadowsocks.CipherType_NONE {
  110. account = serial.ToTypedMessage(&shadowsocks.Account{
  111. Password: user["password"].(string),
  112. CipherType: ssCipherType,
  113. })
  114. } else {
  115. account = serial.ToTypedMessage(&shadowsocks_2022.ServerConfig{
  116. Key: user["password"].(string),
  117. Email: user["email"].(string),
  118. })
  119. }
  120. default:
  121. return nil
  122. }
  123. client := *x.HandlerServiceClient
  124. _, err := client.AlterInbound(context.Background(), &command.AlterInboundRequest{
  125. Tag: inboundTag,
  126. Operation: serial.ToTypedMessage(&command.AddUserOperation{
  127. User: &protocol.User{
  128. Email: user["email"].(string),
  129. Account: account,
  130. },
  131. }),
  132. })
  133. return err
  134. }
  135. func (x *XrayAPI) RemoveUser(inboundTag, email string) error {
  136. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  137. defer cancel()
  138. op := &command.RemoveUserOperation{Email: email}
  139. req := &command.AlterInboundRequest{
  140. Tag: inboundTag,
  141. Operation: serial.ToTypedMessage(op),
  142. }
  143. _, err := (*x.HandlerServiceClient).AlterInbound(ctx, req)
  144. if err != nil {
  145. return fmt.Errorf("failed to remove user: %w", err)
  146. }
  147. return nil
  148. }
  149. func (x *XrayAPI) GetTraffic(reset bool) ([]*Traffic, []*ClientTraffic, error) {
  150. if x.grpcClient == nil {
  151. return nil, nil, common.NewError("xray api is not initialized")
  152. }
  153. trafficRegex := regexp.MustCompile(`(inbound|outbound)>>>([^>]+)>>>traffic>>>(downlink|uplink)`)
  154. clientTrafficRegex := regexp.MustCompile(`user>>>([^>]+)>>>traffic>>>(downlink|uplink)`)
  155. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  156. defer cancel()
  157. if x.StatsServiceClient == nil {
  158. return nil, nil, common.NewError("xray StatusServiceClient is not initialized")
  159. }
  160. resp, err := (*x.StatsServiceClient).QueryStats(ctx, &statsService.QueryStatsRequest{Reset_: reset})
  161. if err != nil {
  162. logger.Debug("Failed to query Xray stats:", err)
  163. return nil, nil, err
  164. }
  165. tagTrafficMap := make(map[string]*Traffic)
  166. emailTrafficMap := make(map[string]*ClientTraffic)
  167. for _, stat := range resp.GetStat() {
  168. if matches := trafficRegex.FindStringSubmatch(stat.Name); len(matches) == 4 {
  169. processTraffic(matches, stat.Value, tagTrafficMap)
  170. } else if matches := clientTrafficRegex.FindStringSubmatch(stat.Name); len(matches) == 3 {
  171. processClientTraffic(matches, stat.Value, emailTrafficMap)
  172. }
  173. }
  174. return mapToSlice(tagTrafficMap), mapToSlice(emailTrafficMap), nil
  175. }
  176. func processTraffic(matches []string, value int64, trafficMap map[string]*Traffic) {
  177. isInbound := matches[1] == "inbound"
  178. tag := matches[2]
  179. isDown := matches[3] == "downlink"
  180. if tag == "api" {
  181. return
  182. }
  183. traffic, ok := trafficMap[tag]
  184. if !ok {
  185. traffic = &Traffic{
  186. IsInbound: isInbound,
  187. IsOutbound: !isInbound,
  188. Tag: tag,
  189. }
  190. trafficMap[tag] = traffic
  191. }
  192. if isDown {
  193. traffic.Down = value
  194. } else {
  195. traffic.Up = value
  196. }
  197. }
  198. func processClientTraffic(matches []string, value int64, clientTrafficMap map[string]*ClientTraffic) {
  199. email := matches[1]
  200. isDown := matches[2] == "downlink"
  201. traffic, ok := clientTrafficMap[email]
  202. if !ok {
  203. traffic = &ClientTraffic{Email: email}
  204. clientTrafficMap[email] = traffic
  205. }
  206. if isDown {
  207. traffic.Down = value
  208. } else {
  209. traffic.Up = value
  210. }
  211. }
  212. func mapToSlice[T any](m map[string]*T) []*T {
  213. result := make([]*T, 0, len(m))
  214. for _, v := range m {
  215. result = append(result, v)
  216. }
  217. return result
  218. }