xray.go 6.9 KB

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