process.go 4.8 KB

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