process.go 6.3 KB

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