xray.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. package service
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "runtime"
  6. "sync"
  7. "github.com/mhsanaei/3x-ui/v2/logger"
  8. "github.com/mhsanaei/3x-ui/v2/xray"
  9. "go.uber.org/atomic"
  10. )
  11. var (
  12. p *xray.Process
  13. lock sync.Mutex
  14. isNeedXrayRestart atomic.Bool // Indicates that restart was requested for Xray
  15. isManuallyStopped atomic.Bool // Indicates that Xray was stopped manually from the panel
  16. result string
  17. )
  18. // XrayService provides business logic for Xray process management.
  19. // It handles starting, stopping, restarting Xray, and managing its configuration.
  20. type XrayService struct {
  21. inboundService InboundService
  22. settingService SettingService
  23. xrayAPI xray.XrayAPI
  24. }
  25. // IsXrayRunning checks if the Xray process is currently running.
  26. func (s *XrayService) IsXrayRunning() bool {
  27. return p != nil && p.IsRunning()
  28. }
  29. // GetXrayErr returns the error from the Xray process, if any.
  30. func (s *XrayService) GetXrayErr() error {
  31. if p == nil {
  32. return nil
  33. }
  34. err := p.GetErr()
  35. if err == nil {
  36. return nil
  37. }
  38. if runtime.GOOS == "windows" && err.Error() == "exit status 1" {
  39. // exit status 1 on Windows means that Xray process was killed
  40. // as we kill process to stop in on Windows, this is not an error
  41. return nil
  42. }
  43. return err
  44. }
  45. // GetXrayResult returns the result string from the Xray process.
  46. func (s *XrayService) GetXrayResult() string {
  47. if result != "" {
  48. return result
  49. }
  50. if s.IsXrayRunning() {
  51. return ""
  52. }
  53. if p == nil {
  54. return ""
  55. }
  56. result = p.GetResult()
  57. if runtime.GOOS == "windows" && result == "exit status 1" {
  58. // exit status 1 on Windows means that Xray process was killed
  59. // as we kill process to stop in on Windows, this is not an error
  60. return ""
  61. }
  62. return result
  63. }
  64. // GetXrayVersion returns the version of the running Xray process.
  65. func (s *XrayService) GetXrayVersion() string {
  66. if p == nil {
  67. return "Unknown"
  68. }
  69. return p.GetVersion()
  70. }
  71. // RemoveIndex removes an element at the specified index from a slice.
  72. // Returns a new slice with the element removed.
  73. func RemoveIndex(s []any, index int) []any {
  74. return append(s[:index], s[index+1:]...)
  75. }
  76. // GetXrayConfig retrieves and builds the Xray configuration from settings and inbounds.
  77. func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
  78. templateConfig, err := s.settingService.GetXrayConfigTemplate()
  79. if err != nil {
  80. return nil, err
  81. }
  82. xrayConfig := &xray.Config{}
  83. err = json.Unmarshal([]byte(templateConfig), xrayConfig)
  84. if err != nil {
  85. return nil, err
  86. }
  87. s.inboundService.AddTraffic(nil, nil)
  88. inbounds, err := s.inboundService.GetAllInbounds()
  89. if err != nil {
  90. return nil, err
  91. }
  92. for _, inbound := range inbounds {
  93. if !inbound.Enable {
  94. continue
  95. }
  96. // get settings clients
  97. settings := map[string]any{}
  98. json.Unmarshal([]byte(inbound.Settings), &settings)
  99. clients, ok := settings["clients"].([]any)
  100. if ok {
  101. // check users active or not
  102. clientStats := inbound.ClientStats
  103. for _, clientTraffic := range clientStats {
  104. indexDecrease := 0
  105. for index, client := range clients {
  106. c := client.(map[string]any)
  107. if c["email"] == clientTraffic.Email {
  108. if !clientTraffic.Enable {
  109. clients = RemoveIndex(clients, index-indexDecrease)
  110. indexDecrease++
  111. logger.Infof("Remove Inbound User %s due to expiration or traffic limit", c["email"])
  112. }
  113. }
  114. }
  115. }
  116. // clear client config for additional parameters
  117. var final_clients []any
  118. for _, client := range clients {
  119. c := client.(map[string]any)
  120. if c["enable"] != nil {
  121. if enable, ok := c["enable"].(bool); ok && !enable {
  122. continue
  123. }
  124. }
  125. for key := range c {
  126. if key != "email" && key != "id" && key != "password" && key != "flow" && key != "method" {
  127. delete(c, key)
  128. }
  129. if c["flow"] == "xtls-rprx-vision-udp443" {
  130. c["flow"] = "xtls-rprx-vision"
  131. }
  132. }
  133. final_clients = append(final_clients, any(c))
  134. }
  135. settings["clients"] = final_clients
  136. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  137. if err != nil {
  138. return nil, err
  139. }
  140. inbound.Settings = string(modifiedSettings)
  141. }
  142. if len(inbound.StreamSettings) > 0 {
  143. // Unmarshal stream JSON
  144. var stream map[string]any
  145. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  146. // Remove the "settings" field under "tlsSettings" and "realitySettings"
  147. tlsSettings, ok1 := stream["tlsSettings"].(map[string]any)
  148. realitySettings, ok2 := stream["realitySettings"].(map[string]any)
  149. if ok1 || ok2 {
  150. if ok1 {
  151. delete(tlsSettings, "settings")
  152. } else if ok2 {
  153. delete(realitySettings, "settings")
  154. }
  155. }
  156. delete(stream, "externalProxy")
  157. newStream, err := json.MarshalIndent(stream, "", " ")
  158. if err != nil {
  159. return nil, err
  160. }
  161. inbound.StreamSettings = string(newStream)
  162. }
  163. inboundConfig := inbound.GenXrayInboundConfig()
  164. xrayConfig.InboundConfigs = append(xrayConfig.InboundConfigs, *inboundConfig)
  165. }
  166. return xrayConfig, nil
  167. }
  168. // GetXrayTraffic fetches the current traffic statistics from the running Xray process.
  169. func (s *XrayService) GetXrayTraffic() ([]*xray.Traffic, []*xray.ClientTraffic, error) {
  170. if !s.IsXrayRunning() {
  171. err := errors.New("xray is not running")
  172. logger.Debug("Attempted to fetch Xray traffic, but Xray is not running:", err)
  173. return nil, nil, err
  174. }
  175. apiPort := p.GetAPIPort()
  176. s.xrayAPI.Init(apiPort)
  177. defer s.xrayAPI.Close()
  178. traffic, clientTraffic, err := s.xrayAPI.GetTraffic(true)
  179. if err != nil {
  180. logger.Debug("Failed to fetch Xray traffic:", err)
  181. return nil, nil, err
  182. }
  183. return traffic, clientTraffic, nil
  184. }
  185. // RestartXray restarts the Xray process, optionally forcing a restart even if config unchanged.
  186. func (s *XrayService) RestartXray(isForce bool) error {
  187. lock.Lock()
  188. defer lock.Unlock()
  189. logger.Debug("restart Xray, force:", isForce)
  190. isManuallyStopped.Store(false)
  191. xrayConfig, err := s.GetXrayConfig()
  192. if err != nil {
  193. return err
  194. }
  195. if s.IsXrayRunning() {
  196. if !isForce && p.GetConfig().Equals(xrayConfig) && !isNeedXrayRestart.Load() {
  197. logger.Debug("It does not need to restart Xray")
  198. return nil
  199. }
  200. p.Stop()
  201. }
  202. p = xray.NewProcess(xrayConfig)
  203. result = ""
  204. err = p.Start()
  205. if err != nil {
  206. return err
  207. }
  208. return nil
  209. }
  210. // StopXray stops the running Xray process.
  211. func (s *XrayService) StopXray() error {
  212. lock.Lock()
  213. defer lock.Unlock()
  214. isManuallyStopped.Store(true)
  215. logger.Debug("Attempting to stop Xray...")
  216. if s.IsXrayRunning() {
  217. return p.Stop()
  218. }
  219. return errors.New("xray is not running")
  220. }
  221. // SetToNeedRestart marks that Xray needs to be restarted.
  222. func (s *XrayService) SetToNeedRestart() {
  223. isNeedXrayRestart.Store(true)
  224. }
  225. // IsNeedRestartAndSetFalse checks if restart is needed and resets the flag to false.
  226. func (s *XrayService) IsNeedRestartAndSetFalse() bool {
  227. return isNeedXrayRestart.CompareAndSwap(true, false)
  228. }
  229. // DidXrayCrash checks if Xray crashed by verifying it's not running and wasn't manually stopped.
  230. func (s *XrayService) DidXrayCrash() bool {
  231. return !s.IsXrayRunning() && !isManuallyStopped.Load()
  232. }