process.go 6.1 KB

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