api.go 6.2 KB

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