api.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 "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() ([]*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_: false})
  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. lastValue, ok := x.StatsLastValues[stat.Name]
  262. x.StatsLastValues[stat.Name] = stat.Value
  263. if !ok || stat.Value < lastValue {
  264. // skip first time of seen stat
  265. continue
  266. }
  267. value := stat.Value - lastValue
  268. if matches := trafficRegex.FindStringSubmatch(stat.Name); len(matches) == 4 {
  269. processTraffic(matches, value, tagTrafficMap)
  270. } else if matches := clientTrafficRegex.FindStringSubmatch(stat.Name); len(matches) == 3 {
  271. processClientTraffic(matches, value, emailTrafficMap)
  272. }
  273. }
  274. return mapToSlice(tagTrafficMap), mapToSlice(emailTrafficMap), nil
  275. }
  276. // processTraffic aggregates a traffic stat into trafficMap using regex matches and value.
  277. func processTraffic(matches []string, value int64, trafficMap map[string]*Traffic) {
  278. isInbound := matches[1] == "inbound"
  279. tag := matches[2]
  280. isDown := matches[3] == "downlink"
  281. if tag == "api" {
  282. return
  283. }
  284. traffic, ok := trafficMap[tag]
  285. if !ok {
  286. traffic = &Traffic{
  287. IsInbound: isInbound,
  288. IsOutbound: !isInbound,
  289. Tag: tag,
  290. }
  291. trafficMap[tag] = traffic
  292. }
  293. if isDown {
  294. traffic.Down = value
  295. } else {
  296. traffic.Up = value
  297. }
  298. }
  299. // processClientTraffic updates clientTrafficMap with upload/download values for a client email.
  300. func processClientTraffic(matches []string, value int64, clientTrafficMap map[string]*ClientTraffic) {
  301. email := matches[1]
  302. isDown := matches[2] == "downlink"
  303. traffic, ok := clientTrafficMap[email]
  304. if !ok {
  305. traffic = &ClientTraffic{Email: email}
  306. clientTrafficMap[email] = traffic
  307. }
  308. if isDown {
  309. traffic.Down = value
  310. } else {
  311. traffic.Up = value
  312. }
  313. }
  314. // mapToSlice converts a map of pointers to a slice of pointers.
  315. func mapToSlice[T any](m map[string]*T) []*T {
  316. result := make([]*T, 0, len(m))
  317. for _, v := range m {
  318. result = append(result, v)
  319. }
  320. return result
  321. }