1
0

api.go 6.0 KB

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