api.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. // Package xray provides integration with the Xray proxy core.
  2. // It includes API client functionality, configuration management, traffic monitoring,
  3. // and process control for Xray instances.
  4. package xray
  5. import (
  6. "context"
  7. "encoding/json"
  8. "fmt"
  9. "math"
  10. "regexp"
  11. "time"
  12. "github.com/mhsanaei/3x-ui/v2/logger"
  13. "github.com/mhsanaei/3x-ui/v2/util/common"
  14. "github.com/xtls/xray-core/app/proxyman/command"
  15. statsService "github.com/xtls/xray-core/app/stats/command"
  16. "github.com/xtls/xray-core/common/protocol"
  17. "github.com/xtls/xray-core/common/serial"
  18. "github.com/xtls/xray-core/infra/conf"
  19. "github.com/xtls/xray-core/proxy/shadowsocks"
  20. "github.com/xtls/xray-core/proxy/shadowsocks_2022"
  21. "github.com/xtls/xray-core/proxy/trojan"
  22. "github.com/xtls/xray-core/proxy/vless"
  23. "github.com/xtls/xray-core/proxy/vmess"
  24. "google.golang.org/grpc"
  25. "google.golang.org/grpc/credentials/insecure"
  26. )
  27. // XrayAPI is a gRPC client for managing Xray core configuration, inbounds, outbounds, and statistics.
  28. type XrayAPI struct {
  29. HandlerServiceClient *command.HandlerServiceClient
  30. StatsServiceClient *statsService.StatsServiceClient
  31. grpcClient *grpc.ClientConn
  32. isConnected bool
  33. }
  34. // Init connects to the Xray API server and initializes handler and stats service clients.
  35. func (x *XrayAPI) Init(apiPort int) error {
  36. if apiPort <= 0 || apiPort > math.MaxUint16 {
  37. return fmt.Errorf("invalid Xray API port: %d", apiPort)
  38. }
  39. addr := fmt.Sprintf("127.0.0.1:%d", apiPort)
  40. conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
  41. if err != nil {
  42. return fmt.Errorf("failed to connect to Xray API: %w", err)
  43. }
  44. x.grpcClient = conn
  45. x.isConnected = true
  46. hsClient := command.NewHandlerServiceClient(conn)
  47. ssClient := statsService.NewStatsServiceClient(conn)
  48. x.HandlerServiceClient = &hsClient
  49. x.StatsServiceClient = &ssClient
  50. return nil
  51. }
  52. // Close closes the gRPC connection and resets the XrayAPI client state.
  53. func (x *XrayAPI) Close() {
  54. if x.grpcClient != nil {
  55. x.grpcClient.Close()
  56. }
  57. x.HandlerServiceClient = nil
  58. x.StatsServiceClient = nil
  59. x.isConnected = false
  60. }
  61. // AddInbound adds a new inbound configuration to the Xray core via gRPC.
  62. func (x *XrayAPI) AddInbound(inbound []byte) error {
  63. client := *x.HandlerServiceClient
  64. conf := new(conf.InboundDetourConfig)
  65. err := json.Unmarshal(inbound, conf)
  66. if err != nil {
  67. logger.Debug("Failed to unmarshal inbound:", err)
  68. return err
  69. }
  70. config, err := conf.Build()
  71. if err != nil {
  72. logger.Debug("Failed to build inbound Detur:", err)
  73. return err
  74. }
  75. inboundConfig := command.AddInboundRequest{Inbound: config}
  76. _, err = client.AddInbound(context.Background(), &inboundConfig)
  77. return err
  78. }
  79. // DelInbound removes an inbound configuration from the Xray core by tag.
  80. func (x *XrayAPI) DelInbound(tag string) error {
  81. client := *x.HandlerServiceClient
  82. _, err := client.RemoveInbound(context.Background(), &command.RemoveInboundRequest{
  83. Tag: tag,
  84. })
  85. return err
  86. }
  87. // AddUser adds a user to an inbound in the Xray core using the specified protocol and user data.
  88. func (x *XrayAPI) AddUser(Protocol string, inboundTag string, user map[string]any) error {
  89. var account *serial.TypedMessage
  90. switch Protocol {
  91. case "vmess":
  92. account = serial.ToTypedMessage(&vmess.Account{
  93. Id: user["id"].(string),
  94. })
  95. case "vless":
  96. account = serial.ToTypedMessage(&vless.Account{
  97. Id: user["id"].(string),
  98. Flow: user["flow"].(string),
  99. })
  100. case "trojan":
  101. account = serial.ToTypedMessage(&trojan.Account{
  102. Password: user["password"].(string),
  103. })
  104. case "shadowsocks":
  105. var ssCipherType shadowsocks.CipherType
  106. switch user["cipher"].(string) {
  107. case "aes-128-gcm":
  108. ssCipherType = shadowsocks.CipherType_AES_128_GCM
  109. case "aes-256-gcm":
  110. ssCipherType = shadowsocks.CipherType_AES_256_GCM
  111. case "chacha20-poly1305", "chacha20-ietf-poly1305":
  112. ssCipherType = shadowsocks.CipherType_CHACHA20_POLY1305
  113. case "xchacha20-poly1305", "xchacha20-ietf-poly1305":
  114. ssCipherType = shadowsocks.CipherType_XCHACHA20_POLY1305
  115. default:
  116. ssCipherType = shadowsocks.CipherType_NONE
  117. }
  118. if ssCipherType != shadowsocks.CipherType_NONE {
  119. account = serial.ToTypedMessage(&shadowsocks.Account{
  120. Password: user["password"].(string),
  121. CipherType: ssCipherType,
  122. })
  123. } else {
  124. account = serial.ToTypedMessage(&shadowsocks_2022.ServerConfig{
  125. Key: user["password"].(string),
  126. Email: user["email"].(string),
  127. })
  128. }
  129. default:
  130. return nil
  131. }
  132. client := *x.HandlerServiceClient
  133. _, err := client.AlterInbound(context.Background(), &command.AlterInboundRequest{
  134. Tag: inboundTag,
  135. Operation: serial.ToTypedMessage(&command.AddUserOperation{
  136. User: &protocol.User{
  137. Email: user["email"].(string),
  138. Account: account,
  139. },
  140. }),
  141. })
  142. return err
  143. }
  144. // RemoveUser removes a user from an inbound in the Xray core by email.
  145. func (x *XrayAPI) RemoveUser(inboundTag, email string) error {
  146. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  147. defer cancel()
  148. op := &command.RemoveUserOperation{Email: email}
  149. req := &command.AlterInboundRequest{
  150. Tag: inboundTag,
  151. Operation: serial.ToTypedMessage(op),
  152. }
  153. _, err := (*x.HandlerServiceClient).AlterInbound(ctx, req)
  154. if err != nil {
  155. return fmt.Errorf("failed to remove user: %w", err)
  156. }
  157. return nil
  158. }
  159. // GetTraffic queries traffic statistics from the Xray core, optionally resetting counters.
  160. func (x *XrayAPI) GetTraffic(reset bool) ([]*Traffic, []*ClientTraffic, error) {
  161. if x.grpcClient == nil {
  162. return nil, nil, common.NewError("xray api is not initialized")
  163. }
  164. trafficRegex := regexp.MustCompile(`(inbound|outbound)>>>([^>]+)>>>traffic>>>(downlink|uplink)`)
  165. clientTrafficRegex := regexp.MustCompile(`user>>>([^>]+)>>>traffic>>>(downlink|uplink)`)
  166. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  167. defer cancel()
  168. if x.StatsServiceClient == nil {
  169. return nil, nil, common.NewError("xray StatusServiceClient is not initialized")
  170. }
  171. resp, err := (*x.StatsServiceClient).QueryStats(ctx, &statsService.QueryStatsRequest{Reset_: reset})
  172. if err != nil {
  173. logger.Debug("Failed to query Xray stats:", err)
  174. return nil, nil, err
  175. }
  176. tagTrafficMap := make(map[string]*Traffic)
  177. emailTrafficMap := make(map[string]*ClientTraffic)
  178. for _, stat := range resp.GetStat() {
  179. if matches := trafficRegex.FindStringSubmatch(stat.Name); len(matches) == 4 {
  180. processTraffic(matches, stat.Value, tagTrafficMap)
  181. } else if matches := clientTrafficRegex.FindStringSubmatch(stat.Name); len(matches) == 3 {
  182. processClientTraffic(matches, stat.Value, emailTrafficMap)
  183. }
  184. }
  185. return mapToSlice(tagTrafficMap), mapToSlice(emailTrafficMap), nil
  186. }
  187. // processTraffic aggregates a traffic stat into trafficMap using regex matches and value.
  188. func processTraffic(matches []string, value int64, trafficMap map[string]*Traffic) {
  189. isInbound := matches[1] == "inbound"
  190. tag := matches[2]
  191. isDown := matches[3] == "downlink"
  192. if tag == "api" {
  193. return
  194. }
  195. traffic, ok := trafficMap[tag]
  196. if !ok {
  197. traffic = &Traffic{
  198. IsInbound: isInbound,
  199. IsOutbound: !isInbound,
  200. Tag: tag,
  201. }
  202. trafficMap[tag] = traffic
  203. }
  204. if isDown {
  205. traffic.Down = value
  206. } else {
  207. traffic.Up = value
  208. }
  209. }
  210. // processClientTraffic updates clientTrafficMap with upload/download values for a client email.
  211. func processClientTraffic(matches []string, value int64, clientTrafficMap map[string]*ClientTraffic) {
  212. email := matches[1]
  213. isDown := matches[2] == "downlink"
  214. traffic, ok := clientTrafficMap[email]
  215. if !ok {
  216. traffic = &ClientTraffic{Email: email}
  217. clientTrafficMap[email] = traffic
  218. }
  219. if isDown {
  220. traffic.Down = value
  221. } else {
  222. traffic.Up = value
  223. }
  224. }
  225. // mapToSlice converts a map of pointers to a slice of pointers.
  226. func mapToSlice[T any](m map[string]*T) []*T {
  227. result := make([]*T, 0, len(m))
  228. for _, v := range m {
  229. result = append(result, v)
  230. }
  231. return result
  232. }