api.go 10.0 KB

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