1
0

api.go 6.6 KB

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