xray.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. package service
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "runtime"
  6. "sync"
  7. "github.com/mhsanaei/3x-ui/v3/logger"
  8. "github.com/mhsanaei/3x-ui/v3/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. if inbound.NodeID != nil {
  97. continue
  98. }
  99. // get settings clients
  100. settings := map[string]any{}
  101. json.Unmarshal([]byte(inbound.Settings), &settings)
  102. clients, ok := settings["clients"].([]any)
  103. if ok {
  104. // Fast O(N) lookup map for client traffic enablement
  105. clientStats := inbound.ClientStats
  106. enableMap := make(map[string]bool, len(clientStats))
  107. for _, clientTraffic := range clientStats {
  108. enableMap[clientTraffic.Email] = clientTraffic.Enable
  109. }
  110. // filter and clean clients
  111. var final_clients []any
  112. for _, client := range clients {
  113. c, ok := client.(map[string]any)
  114. if !ok {
  115. continue
  116. }
  117. email, _ := c["email"].(string)
  118. // check users active or not via stats
  119. if enable, exists := enableMap[email]; exists && !enable {
  120. logger.Infof("Remove Inbound User %s due to expiration or traffic limit", email)
  121. continue
  122. }
  123. // check manual disabled flag
  124. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  125. continue
  126. }
  127. // clear client config for additional parameters
  128. for key := range c {
  129. if key != "email" && key != "id" && key != "password" && key != "flow" && key != "method" && key != "auth" && key != "reverse" {
  130. delete(c, key)
  131. }
  132. if flow, ok := c["flow"].(string); ok && flow == "xtls-rprx-vision-udp443" {
  133. c["flow"] = "xtls-rprx-vision"
  134. }
  135. }
  136. final_clients = append(final_clients, any(c))
  137. }
  138. settings["clients"] = final_clients
  139. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  140. if err != nil {
  141. return nil, err
  142. }
  143. inbound.Settings = string(modifiedSettings)
  144. }
  145. if len(inbound.StreamSettings) > 0 {
  146. // Unmarshal stream JSON
  147. var stream map[string]any
  148. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  149. // Remove the "settings" field under "tlsSettings" and "realitySettings"
  150. tlsSettings, ok1 := stream["tlsSettings"].(map[string]any)
  151. realitySettings, ok2 := stream["realitySettings"].(map[string]any)
  152. if ok1 || ok2 {
  153. if ok1 {
  154. delete(tlsSettings, "settings")
  155. } else if ok2 {
  156. delete(realitySettings, "settings")
  157. }
  158. }
  159. delete(stream, "externalProxy")
  160. newStream, err := json.MarshalIndent(stream, "", " ")
  161. if err != nil {
  162. return nil, err
  163. }
  164. inbound.StreamSettings = string(newStream)
  165. }
  166. inboundConfig := inbound.GenXrayInboundConfig()
  167. xrayConfig.InboundConfigs = append(xrayConfig.InboundConfigs, *inboundConfig)
  168. }
  169. return xrayConfig, nil
  170. }
  171. // GetXrayTraffic fetches the current traffic statistics from the running Xray process.
  172. func (s *XrayService) GetXrayTraffic() ([]*xray.Traffic, []*xray.ClientTraffic, error) {
  173. if !s.IsXrayRunning() {
  174. err := errors.New("xray is not running")
  175. logger.Debug("Attempted to fetch Xray traffic, but Xray is not running:", err)
  176. return nil, nil, err
  177. }
  178. apiPort := p.GetAPIPort()
  179. if err := s.xrayAPI.Init(apiPort); err != nil {
  180. logger.Debug("Failed to initialize Xray API:", err)
  181. return nil, nil, err
  182. }
  183. defer s.xrayAPI.Close()
  184. traffic, clientTraffic, err := s.xrayAPI.GetTraffic()
  185. if err != nil {
  186. logger.Debug("Failed to fetch Xray traffic:", err)
  187. return nil, nil, err
  188. }
  189. return traffic, clientTraffic, nil
  190. }
  191. // RestartXray restarts the Xray process, optionally forcing a restart even if config unchanged.
  192. func (s *XrayService) RestartXray(isForce bool) error {
  193. lock.Lock()
  194. defer lock.Unlock()
  195. logger.Debug("restart Xray, force:", isForce)
  196. isManuallyStopped.Store(false)
  197. xrayConfig, err := s.GetXrayConfig()
  198. if err != nil {
  199. return err
  200. }
  201. if s.IsXrayRunning() {
  202. if !isForce && p.GetConfig().Equals(xrayConfig) && !isNeedXrayRestart.Load() {
  203. logger.Debug("It does not need to restart Xray")
  204. return nil
  205. }
  206. p.Stop()
  207. }
  208. p = xray.NewProcess(xrayConfig)
  209. result = ""
  210. s.xrayAPI.StatsLastValues = nil
  211. err = p.Start()
  212. if err != nil {
  213. return err
  214. }
  215. return nil
  216. }
  217. // StopXray stops the running Xray process.
  218. func (s *XrayService) StopXray() error {
  219. lock.Lock()
  220. defer lock.Unlock()
  221. isManuallyStopped.Store(true)
  222. logger.Debug("Attempting to stop Xray...")
  223. if s.IsXrayRunning() {
  224. return p.Stop()
  225. }
  226. return errors.New("xray is not running")
  227. }
  228. // SetToNeedRestart marks that Xray needs to be restarted.
  229. func (s *XrayService) SetToNeedRestart() {
  230. isNeedXrayRestart.Store(true)
  231. }
  232. // GetXrayAPIPort returns the port the local xray process is listening on
  233. // for its gRPC HandlerService, or 0 when xray isn't currently running.
  234. // Exposed for the runtime package's LocalRuntime adapter — runtime can't
  235. // reach into the package-level `p` directly without a service-package
  236. // import cycle.
  237. func (s *XrayService) GetXrayAPIPort() int {
  238. if p == nil || !p.IsRunning() {
  239. return 0
  240. }
  241. return p.GetAPIPort()
  242. }
  243. // IsNeedRestartAndSetFalse checks if restart is needed and resets the flag to false.
  244. func (s *XrayService) IsNeedRestartAndSetFalse() bool {
  245. return isNeedXrayRestart.CompareAndSwap(true, false)
  246. }
  247. // DidXrayCrash checks if Xray crashed by verifying it's not running and wasn't manually stopped.
  248. func (s *XrayService) DidXrayCrash() bool {
  249. return !s.IsXrayRunning() && !isManuallyStopped.Load()
  250. }