process.go 4.7 KB

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