api.go 10 KB

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