api.go 8.8 KB

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