1
0

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