1
0

process.go 6.3 KB

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