api.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 "chacha20-poly1305", "chacha20-ietf-poly1305":
  182. ssCipherType = shadowsocks.CipherType_CHACHA20_POLY1305
  183. case "xchacha20-poly1305", "xchacha20-ietf-poly1305":
  184. ssCipherType = shadowsocks.CipherType_XCHACHA20_POLY1305
  185. default:
  186. ssCipherType = shadowsocks.CipherType_NONE
  187. }
  188. if ssCipherType != shadowsocks.CipherType_NONE {
  189. account = serial.ToTypedMessage(&shadowsocks.Account{
  190. Password: password,
  191. CipherType: ssCipherType,
  192. })
  193. } else {
  194. account = serial.ToTypedMessage(&shadowsocks_2022.ServerConfig{
  195. Key: password,
  196. Email: userEmail,
  197. })
  198. }
  199. case "hysteria", "hysteria2":
  200. auth, err := getRequiredUserString(user, "auth")
  201. if err != nil {
  202. return err
  203. }
  204. account = serial.ToTypedMessage(&hysteriaAccount.Account{
  205. Auth: auth,
  206. })
  207. default:
  208. return nil
  209. }
  210. client := *x.HandlerServiceClient
  211. _, err = client.AlterInbound(context.Background(), &command.AlterInboundRequest{
  212. Tag: inboundTag,
  213. Operation: serial.ToTypedMessage(&command.AddUserOperation{
  214. User: &protocol.User{
  215. Email: userEmail,
  216. Account: account,
  217. },
  218. }),
  219. })
  220. return err
  221. }
  222. // RemoveUser removes a user from an inbound in the Xray core by email.
  223. func (x *XrayAPI) RemoveUser(inboundTag, email string) error {
  224. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  225. defer cancel()
  226. op := &command.RemoveUserOperation{Email: email}
  227. req := &command.AlterInboundRequest{
  228. Tag: inboundTag,
  229. Operation: serial.ToTypedMessage(op),
  230. }
  231. _, err := (*x.HandlerServiceClient).AlterInbound(ctx, req)
  232. if err != nil {
  233. return fmt.Errorf("failed to remove user: %w", err)
  234. }
  235. return nil
  236. }
  237. // GetTraffic queries traffic statistics from the Xray core, optionally resetting counters.
  238. func (x *XrayAPI) GetTraffic(reset bool) ([]*Traffic, []*ClientTraffic, error) {
  239. if x.grpcClient == nil {
  240. return nil, nil, common.NewError("xray api is not initialized")
  241. }
  242. trafficRegex := regexp.MustCompile(`(inbound|outbound)>>>([^>]+)>>>traffic>>>(downlink|uplink)`)
  243. clientTrafficRegex := regexp.MustCompile(`user>>>([^>]+)>>>traffic>>>(downlink|uplink)`)
  244. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  245. defer cancel()
  246. if x.StatsServiceClient == nil {
  247. return nil, nil, common.NewError("xray StatusServiceClient is not initialized")
  248. }
  249. resp, err := (*x.StatsServiceClient).QueryStats(ctx, &statsService.QueryStatsRequest{Reset_: reset})
  250. if err != nil {
  251. logger.Debug("Failed to query Xray stats:", err)
  252. return nil, nil, err
  253. }
  254. tagTrafficMap := make(map[string]*Traffic)
  255. emailTrafficMap := make(map[string]*ClientTraffic)
  256. for _, stat := range resp.GetStat() {
  257. if matches := trafficRegex.FindStringSubmatch(stat.Name); len(matches) == 4 {
  258. processTraffic(matches, stat.Value, tagTrafficMap)
  259. } else if matches := clientTrafficRegex.FindStringSubmatch(stat.Name); len(matches) == 3 {
  260. processClientTraffic(matches, stat.Value, emailTrafficMap)
  261. }
  262. }
  263. return mapToSlice(tagTrafficMap), mapToSlice(emailTrafficMap), nil
  264. }
  265. // processTraffic aggregates a traffic stat into trafficMap using regex matches and value.
  266. func processTraffic(matches []string, value int64, trafficMap map[string]*Traffic) {
  267. isInbound := matches[1] == "inbound"
  268. tag := matches[2]
  269. isDown := matches[3] == "downlink"
  270. if tag == "api" {
  271. return
  272. }
  273. traffic, ok := trafficMap[tag]
  274. if !ok {
  275. traffic = &Traffic{
  276. IsInbound: isInbound,
  277. IsOutbound: !isInbound,
  278. Tag: tag,
  279. }
  280. trafficMap[tag] = traffic
  281. }
  282. if isDown {
  283. traffic.Down = value
  284. } else {
  285. traffic.Up = value
  286. }
  287. }
  288. // processClientTraffic updates clientTrafficMap with upload/download values for a client email.
  289. func processClientTraffic(matches []string, value int64, clientTrafficMap map[string]*ClientTraffic) {
  290. email := matches[1]
  291. isDown := matches[2] == "downlink"
  292. traffic, ok := clientTrafficMap[email]
  293. if !ok {
  294. traffic = &ClientTraffic{Email: email}
  295. clientTrafficMap[email] = traffic
  296. }
  297. if isDown {
  298. traffic.Down = value
  299. } else {
  300. traffic.Up = value
  301. }
  302. }
  303. // mapToSlice converts a map of pointers to a slice of pointers.
  304. func mapToSlice[T any](m map[string]*T) []*T {
  305. result := make([]*T, 0, len(m))
  306. for _, v := range m {
  307. result = append(result, v)
  308. }
  309. return result
  310. }