process.go 5.1 KB

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