1
0

api.go 6.1 KB

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