process.go 5.9 KB

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