process.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. package xray
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io/fs"
  10. "os"
  11. "os/exec"
  12. "regexp"
  13. "runtime"
  14. "strings"
  15. "sync"
  16. "time"
  17. "x-ui/config"
  18. "x-ui/util/common"
  19. "github.com/Workiva/go-datastructures/queue"
  20. statsservice "github.com/xtls/xray-core/app/stats/command"
  21. "google.golang.org/grpc"
  22. "google.golang.org/grpc/credentials/insecure"
  23. )
  24. var trafficRegex = regexp.MustCompile("(inbound|outbound)>>>([^>]+)>>>traffic>>>(downlink|uplink)")
  25. var ClientTrafficRegex = regexp.MustCompile("(user)>>>([^>]+)>>>traffic>>>(downlink|uplink)")
  26. func GetBinaryName() string {
  27. return fmt.Sprintf("xray-%s-%s", runtime.GOOS, runtime.GOARCH)
  28. }
  29. func GetBinaryPath() string {
  30. return config.GetBinFolderPath() + "/" + GetBinaryName()
  31. }
  32. func GetConfigPath() string {
  33. return config.GetBinFolderPath() + "/config.json"
  34. }
  35. func GetGeositePath() string {
  36. return config.GetBinFolderPath() + "/geosite.dat"
  37. }
  38. func GetGeoipPath() string {
  39. return config.GetBinFolderPath() + "/geoip.dat"
  40. }
  41. func GetIranPath() string {
  42. return config.GetBinFolderPath() + "/iran.dat"
  43. }
  44. func GetBlockedIPsPath() string {
  45. return config.GetBinFolderPath() + "/blockedIPs"
  46. }
  47. func stopProcess(p *Process) {
  48. p.Stop()
  49. }
  50. type Process struct {
  51. *process
  52. }
  53. func NewProcess(xrayConfig *Config) *Process {
  54. p := &Process{newProcess(xrayConfig)}
  55. runtime.SetFinalizer(p, stopProcess)
  56. return p
  57. }
  58. type process struct {
  59. cmd *exec.Cmd
  60. version string
  61. apiPort int
  62. config *Config
  63. lines *queue.Queue
  64. exitErr error
  65. }
  66. func newProcess(config *Config) *process {
  67. return &process{
  68. version: "Unknown",
  69. config: config,
  70. lines: queue.New(100),
  71. }
  72. }
  73. func (p *process) IsRunning() bool {
  74. if p.cmd == nil || p.cmd.Process == nil {
  75. return false
  76. }
  77. if p.cmd.ProcessState == nil {
  78. return true
  79. }
  80. return false
  81. }
  82. func (p *process) GetErr() error {
  83. return p.exitErr
  84. }
  85. func (p *process) GetResult() string {
  86. if p.lines.Empty() && p.exitErr != nil {
  87. return p.exitErr.Error()
  88. }
  89. items, _ := p.lines.TakeUntil(func(item interface{}) bool {
  90. return true
  91. })
  92. lines := make([]string, 0, len(items))
  93. for _, item := range items {
  94. lines = append(lines, item.(string))
  95. }
  96. return strings.Join(lines, "\n")
  97. }
  98. func (p *process) GetVersion() string {
  99. return p.version
  100. }
  101. func (p *Process) GetAPIPort() int {
  102. return p.apiPort
  103. }
  104. func (p *Process) GetConfig() *Config {
  105. return p.config
  106. }
  107. func (p *process) refreshAPIPort() {
  108. for _, inbound := range p.config.InboundConfigs {
  109. if inbound.Tag == "api" {
  110. p.apiPort = inbound.Port
  111. break
  112. }
  113. }
  114. }
  115. func (p *process) refreshVersion() {
  116. cmd := exec.Command(GetBinaryPath(), "-version")
  117. data, err := cmd.Output()
  118. if err != nil {
  119. p.version = "Unknown"
  120. } else {
  121. datas := bytes.Split(data, []byte(" "))
  122. if len(datas) <= 1 {
  123. p.version = "Unknown"
  124. } else {
  125. p.version = string(datas[1])
  126. }
  127. }
  128. }
  129. func (p *process) Start() (err error) {
  130. if p.IsRunning() {
  131. return errors.New("xray is already running")
  132. }
  133. defer func() {
  134. if err != nil {
  135. p.exitErr = err
  136. }
  137. }()
  138. data, err := json.MarshalIndent(p.config, "", " ")
  139. if err != nil {
  140. return common.NewErrorf("Failed to generate xray configuration file: %v", err)
  141. }
  142. configPath := GetConfigPath()
  143. err = os.WriteFile(configPath, data, fs.ModePerm)
  144. if err != nil {
  145. return common.NewErrorf("Failed to write configuration file: %v", err)
  146. }
  147. cmd := exec.Command(GetBinaryPath(), "-c", configPath, "-restrictedIPsPath", GetBlockedIPsPath())
  148. p.cmd = cmd
  149. stdReader, err := cmd.StdoutPipe()
  150. if err != nil {
  151. return err
  152. }
  153. errReader, err := cmd.StderrPipe()
  154. if err != nil {
  155. return err
  156. }
  157. var wg sync.WaitGroup
  158. wg.Add(2)
  159. go func() {
  160. defer wg.Done()
  161. reader := bufio.NewReaderSize(stdReader, 8192)
  162. for {
  163. line, _, err := reader.ReadLine()
  164. if err != nil {
  165. return
  166. }
  167. if p.lines.Len() >= 100 {
  168. p.lines.Get(1)
  169. }
  170. p.lines.Put(string(line))
  171. }
  172. }()
  173. go func() {
  174. defer wg.Done()
  175. reader := bufio.NewReaderSize(errReader, 8192)
  176. for {
  177. line, _, err := reader.ReadLine()
  178. if err != nil {
  179. return
  180. }
  181. if p.lines.Len() >= 100 {
  182. p.lines.Get(1)
  183. }
  184. p.lines.Put(string(line))
  185. }
  186. }()
  187. go func() {
  188. err := cmd.Run()
  189. if err != nil {
  190. p.exitErr = err
  191. }
  192. wg.Wait()
  193. }()
  194. p.refreshVersion()
  195. p.refreshAPIPort()
  196. return nil
  197. }
  198. func (p *process) Stop() error {
  199. if !p.IsRunning() {
  200. return errors.New("xray is not running")
  201. }
  202. return p.cmd.Process.Kill()
  203. }
  204. func (p *process) GetTraffic(reset bool) ([]*Traffic, []*ClientTraffic, error) {
  205. if p.apiPort == 0 {
  206. return nil, nil, common.NewError("xray api port wrong:", p.apiPort)
  207. }
  208. conn, err := grpc.Dial(fmt.Sprintf("127.0.0.1:%v", p.apiPort), grpc.WithTransportCredentials(insecure.NewCredentials()))
  209. if err != nil {
  210. return nil, nil, err
  211. }
  212. defer conn.Close()
  213. client := statsservice.NewStatsServiceClient(conn)
  214. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  215. defer cancel()
  216. request := &statsservice.QueryStatsRequest{
  217. Reset_: reset,
  218. }
  219. resp, err := client.QueryStats(ctx, request)
  220. if err != nil {
  221. return nil, nil, err
  222. }
  223. tagTrafficMap := map[string]*Traffic{}
  224. emailTrafficMap := map[string]*ClientTraffic{}
  225. clientTraffics := make([]*ClientTraffic, 0)
  226. traffics := make([]*Traffic, 0)
  227. for _, stat := range resp.GetStat() {
  228. matchs := trafficRegex.FindStringSubmatch(stat.Name)
  229. if len(matchs) < 3 {
  230. matchs := ClientTrafficRegex.FindStringSubmatch(stat.Name)
  231. if len(matchs) < 3 {
  232. continue
  233. } else {
  234. isUser := matchs[1] == "user"
  235. email := matchs[2]
  236. isDown := matchs[3] == "downlink"
  237. if !isUser {
  238. continue
  239. }
  240. traffic, ok := emailTrafficMap[email]
  241. if !ok {
  242. traffic = &ClientTraffic{
  243. Email: email,
  244. }
  245. emailTrafficMap[email] = traffic
  246. clientTraffics = append(clientTraffics, traffic)
  247. }
  248. if isDown {
  249. traffic.Down = stat.Value
  250. } else {
  251. traffic.Up = stat.Value
  252. }
  253. }
  254. continue
  255. }
  256. isInbound := matchs[1] == "inbound"
  257. tag := matchs[2]
  258. isDown := matchs[3] == "downlink"
  259. if tag == "api" {
  260. continue
  261. }
  262. traffic, ok := tagTrafficMap[tag]
  263. if !ok {
  264. traffic = &Traffic{
  265. IsInbound: isInbound,
  266. Tag: tag,
  267. }
  268. tagTrafficMap[tag] = traffic
  269. traffics = append(traffics, traffic)
  270. }
  271. if isDown {
  272. traffic.Down = stat.Value
  273. } else {
  274. traffic.Up = stat.Value
  275. }
  276. }
  277. return traffics, clientTraffics, nil
  278. }