api.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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/trojan"
  17. "github.com/xtls/xray-core/proxy/vless"
  18. "github.com/xtls/xray-core/proxy/vmess"
  19. "google.golang.org/grpc"
  20. "google.golang.org/grpc/credentials/insecure"
  21. )
  22. type XrayAPI struct {
  23. HandlerServiceClient *command.HandlerServiceClient
  24. StatsServiceClient *statsService.StatsServiceClient
  25. grpcClient *grpc.ClientConn
  26. isConnected bool
  27. }
  28. func (x *XrayAPI) Init(apiPort int) (err error) {
  29. if apiPort == 0 {
  30. return common.NewError("xray api port wrong:", apiPort)
  31. }
  32. x.grpcClient, err = grpc.Dial(fmt.Sprintf("127.0.0.1:%v", apiPort), grpc.WithTransportCredentials(insecure.NewCredentials()))
  33. if err != nil {
  34. return err
  35. }
  36. x.isConnected = true
  37. hsClient := command.NewHandlerServiceClient(x.grpcClient)
  38. ssClient := statsService.NewStatsServiceClient(x.grpcClient)
  39. x.HandlerServiceClient = &hsClient
  40. x.StatsServiceClient = &ssClient
  41. return
  42. }
  43. func (x *XrayAPI) Close() {
  44. x.grpcClient.Close()
  45. x.HandlerServiceClient = nil
  46. x.StatsServiceClient = nil
  47. x.isConnected = false
  48. }
  49. func (x *XrayAPI) AddInbound(inbound []byte) error {
  50. client := *x.HandlerServiceClient
  51. conf := new(conf.InboundDetourConfig)
  52. err := json.Unmarshal(inbound, conf)
  53. if err != nil {
  54. logger.Debug("Failed to unmarshal inbound:", err)
  55. }
  56. config, err := conf.Build()
  57. if err != nil {
  58. logger.Debug("Failed to build inbound Detur:", err)
  59. }
  60. inboundConfig := command.AddInboundRequest{Inbound: config}
  61. _, err = client.AddInbound(context.Background(), &inboundConfig)
  62. return err
  63. }
  64. func (x *XrayAPI) DelInbound(tag string) error {
  65. client := *x.HandlerServiceClient
  66. _, err := client.RemoveInbound(context.Background(), &command.RemoveInboundRequest{
  67. Tag: tag,
  68. })
  69. return err
  70. }
  71. func (x *XrayAPI) AddUser(Protocol string, inboundTag string, user map[string]interface{}) error {
  72. var account *serial.TypedMessage
  73. switch Protocol {
  74. case "vmess":
  75. account = serial.ToTypedMessage(&vmess.Account{
  76. Id: user["id"].(string),
  77. })
  78. case "vless":
  79. account = serial.ToTypedMessage(&vless.Account{
  80. Id: user["id"].(string),
  81. Flow: user["flow"].(string),
  82. })
  83. case "trojan":
  84. account = serial.ToTypedMessage(&trojan.Account{
  85. Password: user["password"].(string),
  86. })
  87. case "shadowsocks":
  88. account = serial.ToTypedMessage(&shadowsocks.Account{
  89. Password: user["password"].(string),
  90. })
  91. default:
  92. return nil
  93. }
  94. client := *x.HandlerServiceClient
  95. _, err := client.AlterInbound(context.Background(), &command.AlterInboundRequest{
  96. Tag: inboundTag,
  97. Operation: serial.ToTypedMessage(&command.AddUserOperation{
  98. User: &protocol.User{
  99. Email: user["email"].(string),
  100. Account: account,
  101. },
  102. }),
  103. })
  104. return err
  105. }
  106. func (x *XrayAPI) RemoveUser(inboundTag string, email string) error {
  107. client := *x.HandlerServiceClient
  108. _, err := client.AlterInbound(context.Background(), &command.AlterInboundRequest{
  109. Tag: inboundTag,
  110. Operation: serial.ToTypedMessage(&command.RemoveUserOperation{
  111. Email: email,
  112. }),
  113. })
  114. return err
  115. }
  116. func (x *XrayAPI) GetTraffic(reset bool) ([]*Traffic, []*ClientTraffic, error) {
  117. if x.grpcClient == nil {
  118. return nil, nil, common.NewError("xray api is not initialized")
  119. }
  120. var trafficRegex = regexp.MustCompile("(inbound|outbound)>>>([^>]+)>>>traffic>>>(downlink|uplink)")
  121. var ClientTrafficRegex = regexp.MustCompile("(user)>>>([^>]+)>>>traffic>>>(downlink|uplink)")
  122. client := *x.StatsServiceClient
  123. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  124. defer cancel()
  125. request := &statsService.QueryStatsRequest{
  126. Reset_: reset,
  127. }
  128. resp, err := client.QueryStats(ctx, request)
  129. if err != nil {
  130. return nil, nil, err
  131. }
  132. tagTrafficMap := map[string]*Traffic{}
  133. emailTrafficMap := map[string]*ClientTraffic{}
  134. clientTraffics := make([]*ClientTraffic, 0)
  135. traffics := make([]*Traffic, 0)
  136. for _, stat := range resp.GetStat() {
  137. matchs := trafficRegex.FindStringSubmatch(stat.Name)
  138. if len(matchs) < 3 {
  139. matchs := ClientTrafficRegex.FindStringSubmatch(stat.Name)
  140. if len(matchs) < 3 {
  141. continue
  142. } else {
  143. isUser := matchs[1] == "user"
  144. email := matchs[2]
  145. isDown := matchs[3] == "downlink"
  146. if !isUser {
  147. continue
  148. }
  149. traffic, ok := emailTrafficMap[email]
  150. if !ok {
  151. traffic = &ClientTraffic{
  152. Email: email,
  153. }
  154. emailTrafficMap[email] = traffic
  155. clientTraffics = append(clientTraffics, traffic)
  156. }
  157. if isDown {
  158. traffic.Down = stat.Value
  159. } else {
  160. traffic.Up = stat.Value
  161. }
  162. }
  163. continue
  164. }
  165. isInbound := matchs[1] == "inbound"
  166. tag := matchs[2]
  167. isDown := matchs[3] == "downlink"
  168. if tag == "api" {
  169. continue
  170. }
  171. traffic, ok := tagTrafficMap[tag]
  172. if !ok {
  173. traffic = &Traffic{
  174. IsInbound: isInbound,
  175. Tag: tag,
  176. }
  177. tagTrafficMap[tag] = traffic
  178. traffics = append(traffics, traffic)
  179. }
  180. if isDown {
  181. traffic.Down = stat.Value
  182. } else {
  183. traffic.Up = stat.Value
  184. }
  185. }
  186. return traffics, clientTraffics, nil
  187. }