1
0

process.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. package xray
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/fs"
  9. "os"
  10. "os/exec"
  11. "runtime"
  12. "strings"
  13. "sync"
  14. "syscall"
  15. "time"
  16. "x-ui/config"
  17. "x-ui/logger"
  18. "x-ui/util/common"
  19. "github.com/Workiva/go-datastructures/queue"
  20. )
  21. func GetBinaryName() string {
  22. return fmt.Sprintf("xray-%s-%s", runtime.GOOS, runtime.GOARCH)
  23. }
  24. func GetBinaryPath() string {
  25. return config.GetBinFolderPath() + "/" + GetBinaryName()
  26. }
  27. func GetConfigPath() string {
  28. return config.GetBinFolderPath() + "/config.json"
  29. }
  30. func GetGeositePath() string {
  31. return config.GetBinFolderPath() + "/geosite.dat"
  32. }
  33. func GetGeoipPath() string {
  34. return config.GetBinFolderPath() + "/geoip.dat"
  35. }
  36. func GetIPLimitLogPath() string {
  37. return config.GetLogFolder() + "/3xipl.log"
  38. }
  39. func GetIPLimitBannedLogPath() string {
  40. return config.GetLogFolder() + "/3xipl-banned.log"
  41. }
  42. func GetAccessPersistentLogPath() string {
  43. return config.GetLogFolder() + "/3xipl-access-persistent.log"
  44. }
  45. func GetAccessLogPath() string {
  46. config, err := os.ReadFile(GetConfigPath())
  47. if err != nil {
  48. logger.Warningf("Something went wrong: %s", err)
  49. }
  50. jsonConfig := map[string]interface{}{}
  51. err = json.Unmarshal([]byte(config), &jsonConfig)
  52. if err != nil {
  53. logger.Warningf("Something went wrong: %s", err)
  54. }
  55. if jsonConfig["log"] != nil {
  56. jsonLog := jsonConfig["log"].(map[string]interface{})
  57. if jsonLog["access"] != nil {
  58. accessLogPath := jsonLog["access"].(string)
  59. return accessLogPath
  60. }
  61. }
  62. return ""
  63. }
  64. func stopProcess(p *Process) {
  65. p.Stop()
  66. }
  67. type Process struct {
  68. *process
  69. }
  70. func NewProcess(xrayConfig *Config) *Process {
  71. p := &Process{newProcess(xrayConfig)}
  72. runtime.SetFinalizer(p, stopProcess)
  73. return p
  74. }
  75. type process struct {
  76. cmd *exec.Cmd
  77. version string
  78. apiPort int
  79. config *Config
  80. lines *queue.Queue
  81. exitErr error
  82. startTime time.Time
  83. }
  84. func newProcess(config *Config) *process {
  85. return &process{
  86. version: "Unknown",
  87. config: config,
  88. lines: queue.New(100),
  89. startTime: time.Now(),
  90. }
  91. }
  92. func (p *process) IsRunning() bool {
  93. if p.cmd == nil || p.cmd.Process == nil {
  94. return false
  95. }
  96. if p.cmd.ProcessState == nil {
  97. return true
  98. }
  99. return false
  100. }
  101. func (p *process) GetErr() error {
  102. return p.exitErr
  103. }
  104. func (p *process) GetResult() string {
  105. if p.lines.Empty() && p.exitErr != nil {
  106. return p.exitErr.Error()
  107. }
  108. items, _ := p.lines.TakeUntil(func(item interface{}) bool {
  109. return true
  110. })
  111. lines := make([]string, 0, len(items))
  112. for _, item := range items {
  113. lines = append(lines, item.(string))
  114. }
  115. return strings.Join(lines, "\n")
  116. }
  117. func (p *process) GetVersion() string {
  118. return p.version
  119. }
  120. func (p *Process) GetAPIPort() int {
  121. return p.apiPort
  122. }
  123. func (p *Process) GetConfig() *Config {
  124. return p.config
  125. }
  126. func (p *Process) GetUptime() uint64 {
  127. return uint64(time.Since(p.startTime).Seconds())
  128. }
  129. func (p *process) refreshAPIPort() {
  130. for _, inbound := range p.config.InboundConfigs {
  131. if inbound.Tag == "api" {
  132. p.apiPort = inbound.Port
  133. break
  134. }
  135. }
  136. }
  137. func (p *process) refreshVersion() {
  138. cmd := exec.Command(GetBinaryPath(), "-version")
  139. data, err := cmd.Output()
  140. if err != nil {
  141. p.version = "Unknown"
  142. } else {
  143. datas := bytes.Split(data, []byte(" "))
  144. if len(datas) <= 1 {
  145. p.version = "Unknown"
  146. } else {
  147. p.version = string(datas[1])
  148. }
  149. }
  150. }
  151. func (p *process) Start() (err error) {
  152. if p.IsRunning() {
  153. return errors.New("xray is already running")
  154. }
  155. defer func() {
  156. if err != nil {
  157. p.exitErr = err
  158. }
  159. }()
  160. data, err := json.MarshalIndent(p.config, "", " ")
  161. if err != nil {
  162. return common.NewErrorf("Failed to generate xray configuration file: %v", err)
  163. }
  164. configPath := GetConfigPath()
  165. err = os.WriteFile(configPath, data, fs.ModePerm)
  166. if err != nil {
  167. return common.NewErrorf("Failed to write configuration file: %v", err)
  168. }
  169. cmd := exec.Command(GetBinaryPath(), "-c", configPath)
  170. p.cmd = cmd
  171. stdReader, err := cmd.StdoutPipe()
  172. if err != nil {
  173. return err
  174. }
  175. errReader, err := cmd.StderrPipe()
  176. if err != nil {
  177. return err
  178. }
  179. var wg sync.WaitGroup
  180. wg.Add(2)
  181. go func() {
  182. defer wg.Done()
  183. reader := bufio.NewReaderSize(stdReader, 8192)
  184. for {
  185. line, _, err := reader.ReadLine()
  186. if err != nil {
  187. return
  188. }
  189. if p.lines.Len() >= 100 {
  190. p.lines.Get(1)
  191. }
  192. p.lines.Put(string(line))
  193. }
  194. }()
  195. go func() {
  196. defer wg.Done()
  197. reader := bufio.NewReaderSize(errReader, 8192)
  198. for {
  199. line, _, err := reader.ReadLine()
  200. if err != nil {
  201. return
  202. }
  203. if p.lines.Len() >= 100 {
  204. p.lines.Get(1)
  205. }
  206. p.lines.Put(string(line))
  207. }
  208. }()
  209. go func() {
  210. err := cmd.Run()
  211. if err != nil {
  212. p.exitErr = err
  213. }
  214. wg.Wait()
  215. }()
  216. p.refreshVersion()
  217. p.refreshAPIPort()
  218. return nil
  219. }
  220. func (p *process) Stop() error {
  221. if !p.IsRunning() {
  222. return errors.New("xray is not running")
  223. }
  224. return p.cmd.Process.Signal(syscall.SIGTERM)
  225. }