1
0

process.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. onlineClients []string
  80. config *Config
  81. lines *queue.Queue
  82. exitErr error
  83. startTime time.Time
  84. }
  85. func newProcess(config *Config) *process {
  86. return &process{
  87. version: "Unknown",
  88. config: config,
  89. lines: queue.New(100),
  90. startTime: time.Now(),
  91. }
  92. }
  93. func (p *process) IsRunning() bool {
  94. if p.cmd == nil || p.cmd.Process == nil {
  95. return false
  96. }
  97. if p.cmd.ProcessState == nil {
  98. return true
  99. }
  100. return false
  101. }
  102. func (p *process) GetErr() error {
  103. return p.exitErr
  104. }
  105. func (p *process) GetResult() string {
  106. if p.lines.Empty() && p.exitErr != nil {
  107. return p.exitErr.Error()
  108. }
  109. items, _ := p.lines.TakeUntil(func(item interface{}) bool {
  110. return true
  111. })
  112. lines := make([]string, 0, len(items))
  113. for _, item := range items {
  114. lines = append(lines, item.(string))
  115. }
  116. return strings.Join(lines, "\n")
  117. }
  118. func (p *process) GetVersion() string {
  119. return p.version
  120. }
  121. func (p *Process) GetAPIPort() int {
  122. return p.apiPort
  123. }
  124. func (p *Process) GetConfig() *Config {
  125. return p.config
  126. }
  127. func (p *Process) GetOnlineClients() []string {
  128. return p.onlineClients
  129. }
  130. func (p *Process) SetOnlineClients(users []string) {
  131. p.onlineClients = users
  132. }
  133. func (p *Process) GetUptime() uint64 {
  134. return uint64(time.Since(p.startTime).Seconds())
  135. }
  136. func (p *process) refreshAPIPort() {
  137. for _, inbound := range p.config.InboundConfigs {
  138. if inbound.Tag == "api" {
  139. p.apiPort = inbound.Port
  140. break
  141. }
  142. }
  143. }
  144. func (p *process) refreshVersion() {
  145. cmd := exec.Command(GetBinaryPath(), "-version")
  146. data, err := cmd.Output()
  147. if err != nil {
  148. p.version = "Unknown"
  149. } else {
  150. datas := bytes.Split(data, []byte(" "))
  151. if len(datas) <= 1 {
  152. p.version = "Unknown"
  153. } else {
  154. p.version = string(datas[1])
  155. }
  156. }
  157. }
  158. func (p *process) Start() (err error) {
  159. if p.IsRunning() {
  160. return errors.New("xray is already running")
  161. }
  162. defer func() {
  163. if err != nil {
  164. p.exitErr = err
  165. }
  166. }()
  167. data, err := json.MarshalIndent(p.config, "", " ")
  168. if err != nil {
  169. return common.NewErrorf("Failed to generate xray configuration file: %v", err)
  170. }
  171. configPath := GetConfigPath()
  172. err = os.WriteFile(configPath, data, fs.ModePerm)
  173. if err != nil {
  174. return common.NewErrorf("Failed to write configuration file: %v", err)
  175. }
  176. cmd := exec.Command(GetBinaryPath(), "-c", configPath)
  177. p.cmd = cmd
  178. stdReader, err := cmd.StdoutPipe()
  179. if err != nil {
  180. return err
  181. }
  182. errReader, err := cmd.StderrPipe()
  183. if err != nil {
  184. return err
  185. }
  186. var wg sync.WaitGroup
  187. wg.Add(2)
  188. go func() {
  189. defer wg.Done()
  190. reader := bufio.NewReaderSize(stdReader, 8192)
  191. for {
  192. line, _, err := reader.ReadLine()
  193. if err != nil {
  194. return
  195. }
  196. if p.lines.Len() >= 100 {
  197. p.lines.Get(1)
  198. }
  199. p.lines.Put(string(line))
  200. }
  201. }()
  202. go func() {
  203. defer wg.Done()
  204. reader := bufio.NewReaderSize(errReader, 8192)
  205. for {
  206. line, _, err := reader.ReadLine()
  207. if err != nil {
  208. return
  209. }
  210. if p.lines.Len() >= 100 {
  211. p.lines.Get(1)
  212. }
  213. p.lines.Put(string(line))
  214. }
  215. }()
  216. go func() {
  217. err := cmd.Run()
  218. if err != nil {
  219. p.exitErr = err
  220. }
  221. wg.Wait()
  222. }()
  223. p.refreshVersion()
  224. p.refreshAPIPort()
  225. return nil
  226. }
  227. func (p *process) Stop() error {
  228. if !p.IsRunning() {
  229. return errors.New("xray is not running")
  230. }
  231. return p.cmd.Process.Signal(syscall.SIGTERM)
  232. }