xray.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. package service
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "runtime"
  6. "strings"
  7. "sync"
  8. "github.com/mhsanaei/3x-ui/v3/database/model"
  9. "github.com/mhsanaei/3x-ui/v3/logger"
  10. "github.com/mhsanaei/3x-ui/v3/xray"
  11. "go.uber.org/atomic"
  12. )
  13. var (
  14. p *xray.Process
  15. lock sync.Mutex
  16. isNeedXrayRestart atomic.Bool // Indicates that restart was requested for Xray
  17. isManuallyStopped atomic.Bool // Indicates that Xray was stopped manually from the panel
  18. result string
  19. )
  20. // XrayService provides business logic for Xray process management.
  21. // It handles starting, stopping, restarting Xray, and managing its configuration.
  22. type XrayService struct {
  23. inboundService InboundService
  24. settingService SettingService
  25. xrayAPI xray.XrayAPI
  26. }
  27. // IsXrayRunning checks if the Xray process is currently running.
  28. func (s *XrayService) IsXrayRunning() bool {
  29. return p != nil && p.IsRunning()
  30. }
  31. // GetXrayErr returns the error from the Xray process, if any.
  32. func (s *XrayService) GetXrayErr() error {
  33. if p == nil {
  34. return nil
  35. }
  36. err := p.GetErr()
  37. if err == nil {
  38. return nil
  39. }
  40. if runtime.GOOS == "windows" && err.Error() == "exit status 1" {
  41. // exit status 1 on Windows means that Xray process was killed
  42. // as we kill process to stop in on Windows, this is not an error
  43. return nil
  44. }
  45. return err
  46. }
  47. // GetXrayResult returns the result string from the Xray process.
  48. func (s *XrayService) GetXrayResult() string {
  49. if result != "" {
  50. return result
  51. }
  52. if s.IsXrayRunning() {
  53. return ""
  54. }
  55. if p == nil {
  56. return ""
  57. }
  58. result = p.GetResult()
  59. if runtime.GOOS == "windows" && result == "exit status 1" {
  60. // exit status 1 on Windows means that Xray process was killed
  61. // as we kill process to stop in on Windows, this is not an error
  62. return ""
  63. }
  64. return result
  65. }
  66. // GetXrayVersion returns the version of the running Xray process.
  67. func (s *XrayService) GetXrayVersion() string {
  68. if p == nil {
  69. return "Unknown"
  70. }
  71. return p.GetVersion()
  72. }
  73. // RemoveIndex removes an element at the specified index from a slice.
  74. // Returns a new slice with the element removed.
  75. func RemoveIndex(s []any, index int) []any {
  76. return append(s[:index], s[index+1:]...)
  77. }
  78. // GetXrayConfig retrieves and builds the Xray configuration from settings and inbounds.
  79. func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
  80. templateConfig, err := s.settingService.GetXrayConfigTemplate()
  81. if err != nil {
  82. return nil, err
  83. }
  84. xrayConfig := &xray.Config{}
  85. err = json.Unmarshal([]byte(templateConfig), xrayConfig)
  86. if err != nil {
  87. return nil, err
  88. }
  89. _, _, _ = s.inboundService.AddTraffic(nil, nil)
  90. inbounds, err := s.inboundService.GetAllInbounds()
  91. if err != nil {
  92. return nil, err
  93. }
  94. for _, inbound := range inbounds {
  95. if !inbound.Enable {
  96. continue
  97. }
  98. if inbound.NodeID != nil {
  99. continue
  100. }
  101. settings := map[string]any{}
  102. json.Unmarshal([]byte(inbound.Settings), &settings)
  103. dbClients, listErr := s.inboundService.clientService.ListForInbound(nil, inbound.Id)
  104. if listErr != nil {
  105. return nil, listErr
  106. }
  107. clientStats := inbound.ClientStats
  108. enableMap := make(map[string]bool, len(clientStats))
  109. for _, clientTraffic := range clientStats {
  110. enableMap[clientTraffic.Email] = clientTraffic.Enable
  111. }
  112. var finalClients []any
  113. for i := range dbClients {
  114. c := dbClients[i]
  115. if enable, exists := enableMap[c.Email]; exists && !enable {
  116. logger.Infof("Remove Inbound User %s due to expiration or traffic limit", c.Email)
  117. continue
  118. }
  119. if !c.Enable {
  120. continue
  121. }
  122. flow := c.Flow
  123. if flow == "xtls-rprx-vision-udp443" {
  124. flow = "xtls-rprx-vision"
  125. }
  126. entry := map[string]any{"email": c.Email}
  127. switch inbound.Protocol {
  128. case model.VLESS:
  129. if c.ID != "" {
  130. entry["id"] = c.ID
  131. }
  132. if flow != "" {
  133. entry["flow"] = flow
  134. }
  135. if c.Reverse != nil {
  136. entry["reverse"] = c.Reverse
  137. }
  138. case model.VMESS:
  139. if c.ID != "" {
  140. entry["id"] = c.ID
  141. }
  142. if c.Security != "" {
  143. entry["security"] = c.Security
  144. }
  145. case model.Trojan:
  146. if c.Password != "" {
  147. entry["password"] = c.Password
  148. }
  149. if flow != "" {
  150. entry["flow"] = flow
  151. }
  152. case model.Shadowsocks:
  153. if c.Password != "" {
  154. entry["password"] = c.Password
  155. }
  156. if c.Security != "" {
  157. entry["method"] = c.Security
  158. }
  159. case model.Hysteria, model.Hysteria2:
  160. if c.Auth != "" {
  161. entry["auth"] = c.Auth
  162. }
  163. }
  164. finalClients = append(finalClients, entry)
  165. }
  166. _, hadClients := settings["clients"]
  167. mutated := hadClients || len(finalClients) > 0
  168. if mutated {
  169. settings["clients"] = finalClients
  170. }
  171. if inboundCanHostFallbacks(inbound) {
  172. fallbacks, fbErr := s.inboundService.fallbackService.BuildFallbacksJSON(nil, inbound.Id)
  173. if fbErr != nil {
  174. return nil, fbErr
  175. }
  176. if len(fallbacks) > 0 {
  177. generic := make([]any, 0, len(fallbacks))
  178. for _, f := range fallbacks {
  179. generic = append(generic, f)
  180. }
  181. settings["fallbacks"] = generic
  182. mutated = true
  183. }
  184. }
  185. if mutated {
  186. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  187. if err != nil {
  188. return nil, err
  189. }
  190. inbound.Settings = string(modifiedSettings)
  191. }
  192. if len(inbound.StreamSettings) > 0 {
  193. // Unmarshal stream JSON
  194. var stream map[string]any
  195. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  196. // Remove the "settings" field under "tlsSettings" and "realitySettings"
  197. tlsSettings, ok1 := stream["tlsSettings"].(map[string]any)
  198. realitySettings, ok2 := stream["realitySettings"].(map[string]any)
  199. if ok1 || ok2 {
  200. if ok1 {
  201. delete(tlsSettings, "settings")
  202. } else if ok2 {
  203. delete(realitySettings, "settings")
  204. }
  205. }
  206. delete(stream, "externalProxy")
  207. newStream, err := json.MarshalIndent(stream, "", " ")
  208. if err != nil {
  209. return nil, err
  210. }
  211. inbound.StreamSettings = string(newStream)
  212. }
  213. if inbound.Protocol == model.Shadowsocks {
  214. if healed, ok := healShadowsocksClientMethods(inbound.Settings); ok {
  215. inbound.Settings = healed
  216. }
  217. }
  218. inboundConfig := inbound.GenXrayInboundConfig()
  219. xrayConfig.InboundConfigs = append(xrayConfig.InboundConfigs, *inboundConfig)
  220. }
  221. return xrayConfig, nil
  222. }
  223. // healShadowsocksClientMethods is the same idea as applyShadowsocksClientMethod
  224. // (see client.go) but applied at xray-config-build time, to backfill the
  225. // per-client method field for legacy shadowsocks inbounds whose clients were
  226. // stored before applyShadowsocksClientMethod existed. Returns the rewritten
  227. // settings string and true when anything actually changed.
  228. func healShadowsocksClientMethods(settings string) (string, bool) {
  229. if settings == "" {
  230. return settings, false
  231. }
  232. var parsed map[string]any
  233. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  234. return settings, false
  235. }
  236. method, _ := parsed["method"].(string)
  237. if method == "" || strings.HasPrefix(method, "2022-blake3-") {
  238. return settings, false
  239. }
  240. clients, ok := parsed["clients"].([]any)
  241. if !ok {
  242. return settings, false
  243. }
  244. changed := false
  245. for i := range clients {
  246. cm, ok := clients[i].(map[string]any)
  247. if !ok {
  248. continue
  249. }
  250. if existing, _ := cm["method"].(string); existing != "" {
  251. continue
  252. }
  253. cm["method"] = method
  254. clients[i] = cm
  255. changed = true
  256. }
  257. if !changed {
  258. return settings, false
  259. }
  260. out, err := json.MarshalIndent(parsed, "", " ")
  261. if err != nil {
  262. return settings, false
  263. }
  264. return string(out), true
  265. }
  266. // GetXrayTraffic fetches the current traffic statistics from the running Xray process.
  267. func (s *XrayService) GetXrayTraffic() ([]*xray.Traffic, []*xray.ClientTraffic, error) {
  268. if !s.IsXrayRunning() {
  269. err := errors.New("xray is not running")
  270. logger.Debug("Attempted to fetch Xray traffic, but Xray is not running:", err)
  271. return nil, nil, err
  272. }
  273. apiPort := p.GetAPIPort()
  274. if err := s.xrayAPI.Init(apiPort); err != nil {
  275. logger.Debug("Failed to initialize Xray API:", err)
  276. return nil, nil, err
  277. }
  278. defer s.xrayAPI.Close()
  279. traffic, clientTraffic, err := s.xrayAPI.GetTraffic()
  280. if err != nil {
  281. logger.Debug("Failed to fetch Xray traffic:", err)
  282. return nil, nil, err
  283. }
  284. return traffic, clientTraffic, nil
  285. }
  286. // RestartXray restarts the Xray process, optionally forcing a restart even if config unchanged.
  287. func (s *XrayService) RestartXray(isForce bool) error {
  288. lock.Lock()
  289. defer lock.Unlock()
  290. logger.Debug("restart Xray, force:", isForce)
  291. isManuallyStopped.Store(false)
  292. xrayConfig, err := s.GetXrayConfig()
  293. if err != nil {
  294. return err
  295. }
  296. if s.IsXrayRunning() {
  297. if !isForce && p.GetConfig().Equals(xrayConfig) && !isNeedXrayRestart.Load() {
  298. logger.Debug("It does not need to restart Xray")
  299. return nil
  300. }
  301. p.Stop()
  302. }
  303. p = xray.NewProcess(xrayConfig)
  304. result = ""
  305. s.xrayAPI.StatsLastValues = nil
  306. err = p.Start()
  307. if err != nil {
  308. return err
  309. }
  310. return nil
  311. }
  312. // StopXray stops the running Xray process.
  313. func (s *XrayService) StopXray() error {
  314. lock.Lock()
  315. defer lock.Unlock()
  316. isManuallyStopped.Store(true)
  317. logger.Debug("Attempting to stop Xray...")
  318. if s.IsXrayRunning() {
  319. return p.Stop()
  320. }
  321. return errors.New("xray is not running")
  322. }
  323. // SetToNeedRestart marks that Xray needs to be restarted.
  324. func (s *XrayService) SetToNeedRestart() {
  325. isNeedXrayRestart.Store(true)
  326. }
  327. // GetXrayAPIPort returns the port the local xray process is listening on
  328. // for its gRPC HandlerService, or 0 when xray isn't currently running.
  329. // Exposed for the runtime package's LocalRuntime adapter — runtime can't
  330. // reach into the package-level `p` directly without a service-package
  331. // import cycle.
  332. func (s *XrayService) GetXrayAPIPort() int {
  333. if p == nil || !p.IsRunning() {
  334. return 0
  335. }
  336. return p.GetAPIPort()
  337. }
  338. // IsNeedRestartAndSetFalse checks if restart is needed and resets the flag to false.
  339. func (s *XrayService) IsNeedRestartAndSetFalse() bool {
  340. return isNeedXrayRestart.CompareAndSwap(true, false)
  341. }
  342. // DidXrayCrash checks if Xray crashed by verifying it's not running and wasn't manually stopped.
  343. func (s *XrayService) DidXrayCrash() bool {
  344. return !s.IsXrayRunning() && !isManuallyStopped.Load()
  345. }