api.go 6.0 KB

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