process.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 GetBlockedIPsPath() string {
  39. return config.GetBinFolderPath() + "/BlockedIps"
  40. }
  41. func GetIPLimitLogPath() string {
  42. return config.GetLogFolder() + "/3xipl.log"
  43. }
  44. func GetIPLimitBannedLogPath() string {
  45. return config.GetLogFolder() + "/3xipl-banned.log"
  46. }
  47. func GetAccessPersistentLogPath() string {
  48. return config.GetLogFolder() + "/3xipl-access-persistent.log"
  49. }
  50. func GetAccessLogPath() string {
  51. config, err := os.ReadFile(GetConfigPath())
  52. if err != nil {
  53. logger.Warningf("Something went wrong: %s", err)
  54. }
  55. jsonConfig := map[string]interface{}{}
  56. err = json.Unmarshal([]byte(config), &jsonConfig)
  57. if err != nil {
  58. logger.Warningf("Something went wrong: %s", err)
  59. }
  60. if jsonConfig["log"] != nil {
  61. jsonLog := jsonConfig["log"].(map[string]interface{})
  62. if jsonLog["access"] != nil {
  63. accessLogPath := jsonLog["access"].(string)
  64. return accessLogPath
  65. }
  66. }
  67. return ""
  68. }
  69. func stopProcess(p *Process) {
  70. p.Stop()
  71. }
  72. type Process struct {
  73. *process
  74. }
  75. func NewProcess(xrayConfig *Config) *Process {
  76. p := &Process{newProcess(xrayConfig)}
  77. runtime.SetFinalizer(p, stopProcess)
  78. return p
  79. }
  80. type process struct {
  81. cmd *exec.Cmd
  82. version string
  83. apiPort int
  84. config *Config
  85. lines *queue.Queue
  86. exitErr error
  87. }
  88. func newProcess(config *Config) *process {
  89. return &process{
  90. version: "Unknown",
  91. config: config,
  92. lines: queue.New(100),
  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) 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, "-restrictedIPsPath", GetBlockedIPsPath())
  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. }