1
0

api.go 8.6 KB

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