process.go 4.6 KB

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