xray.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. package service
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "path/filepath"
  6. "runtime"
  7. "strings"
  8. "sync"
  9. "github.com/mhsanaei/3x-ui/v3/config"
  10. "github.com/mhsanaei/3x-ui/v3/database/model"
  11. "github.com/mhsanaei/3x-ui/v3/logger"
  12. "github.com/mhsanaei/3x-ui/v3/util/json_util"
  13. "github.com/mhsanaei/3x-ui/v3/xray"
  14. "go.uber.org/atomic"
  15. )
  16. var (
  17. p *xray.Process
  18. lock sync.Mutex
  19. isNeedXrayRestart atomic.Bool // Indicates that restart was requested for Xray
  20. isManuallyStopped atomic.Bool // Indicates that Xray was stopped manually from the panel
  21. result string
  22. )
  23. // XrayService provides business logic for Xray process management.
  24. // It handles starting, stopping, restarting Xray, and managing its configuration.
  25. type XrayService struct {
  26. inboundService InboundService
  27. settingService SettingService
  28. xrayAPI xray.XrayAPI
  29. }
  30. // IsXrayRunning checks if the Xray process is currently running.
  31. func (s *XrayService) IsXrayRunning() bool {
  32. return p != nil && p.IsRunning()
  33. }
  34. // GetXrayErr returns the error from the Xray process, if any.
  35. func (s *XrayService) GetXrayErr() error {
  36. if p == nil {
  37. return nil
  38. }
  39. err := p.GetErr()
  40. if err == nil {
  41. return nil
  42. }
  43. if runtime.GOOS == "windows" && err.Error() == "exit status 1" {
  44. // exit status 1 on Windows means that Xray process was killed
  45. // as we kill process to stop in on Windows, this is not an error
  46. return nil
  47. }
  48. return err
  49. }
  50. // GetXrayResult returns the result string from the Xray process.
  51. func (s *XrayService) GetXrayResult() string {
  52. if result != "" {
  53. return result
  54. }
  55. if s.IsXrayRunning() {
  56. return ""
  57. }
  58. if p == nil {
  59. return ""
  60. }
  61. result = p.GetResult()
  62. if runtime.GOOS == "windows" && result == "exit status 1" {
  63. // exit status 1 on Windows means that Xray process was killed
  64. // as we kill process to stop in on Windows, this is not an error
  65. return ""
  66. }
  67. return result
  68. }
  69. // GetXrayVersion returns the version of the running Xray process.
  70. func (s *XrayService) GetXrayVersion() string {
  71. if p == nil {
  72. return "Unknown"
  73. }
  74. return p.GetVersion()
  75. }
  76. // RemoveIndex removes an element at the specified index from a slice.
  77. // Returns a new slice with the element removed.
  78. func RemoveIndex(s []any, index int) []any {
  79. return append(s[:index], s[index+1:]...)
  80. }
  81. // GetXrayConfig retrieves and builds the Xray configuration from settings and inbounds.
  82. func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
  83. templateConfig, err := s.settingService.GetXrayConfigTemplate()
  84. if err != nil {
  85. return nil, err
  86. }
  87. xrayConfig := &xray.Config{}
  88. err = json.Unmarshal([]byte(templateConfig), xrayConfig)
  89. if err != nil {
  90. return nil, err
  91. }
  92. xrayConfig.LogConfig = resolveXrayLogPaths(xrayConfig.LogConfig)
  93. _, _, _ = s.inboundService.AddTraffic(nil, nil)
  94. inbounds, err := s.inboundService.GetAllInbounds()
  95. if err != nil {
  96. return nil, err
  97. }
  98. for _, inbound := range inbounds {
  99. if !inbound.Enable {
  100. continue
  101. }
  102. if inbound.NodeID != nil {
  103. continue
  104. }
  105. if inbound.Protocol == model.MTProto {
  106. continue
  107. }
  108. settings := map[string]any{}
  109. json.Unmarshal([]byte(inbound.Settings), &settings)
  110. dbClients, listErr := s.inboundService.clientService.ListForInbound(nil, inbound.Id)
  111. if listErr != nil {
  112. return nil, listErr
  113. }
  114. clientStats := inbound.ClientStats
  115. enableMap := make(map[string]bool, len(clientStats))
  116. for _, clientTraffic := range clientStats {
  117. enableMap[clientTraffic.Email] = clientTraffic.Enable
  118. }
  119. var finalClients []any
  120. for i := range dbClients {
  121. c := dbClients[i]
  122. if enable, exists := enableMap[c.Email]; exists && !enable {
  123. logger.Infof("Remove Inbound User %s due to expiration or traffic limit", c.Email)
  124. continue
  125. }
  126. if !c.Enable {
  127. continue
  128. }
  129. flow := c.Flow
  130. if flow == "xtls-rprx-vision-udp443" {
  131. flow = "xtls-rprx-vision"
  132. }
  133. entry := map[string]any{"email": c.Email}
  134. switch inbound.Protocol {
  135. case model.VLESS:
  136. if c.ID != "" {
  137. entry["id"] = c.ID
  138. }
  139. if flow != "" {
  140. entry["flow"] = flow
  141. }
  142. if c.Reverse != nil {
  143. entry["reverse"] = c.Reverse
  144. }
  145. case model.VMESS:
  146. if c.ID != "" {
  147. entry["id"] = c.ID
  148. }
  149. if c.Security != "" {
  150. entry["security"] = c.Security
  151. }
  152. case model.Trojan:
  153. if c.Password != "" {
  154. entry["password"] = c.Password
  155. }
  156. if flow != "" {
  157. entry["flow"] = flow
  158. }
  159. case model.Shadowsocks:
  160. if c.Password != "" {
  161. entry["password"] = c.Password
  162. }
  163. case model.Hysteria:
  164. if c.Auth != "" {
  165. entry["auth"] = c.Auth
  166. }
  167. }
  168. finalClients = append(finalClients, entry)
  169. }
  170. _, hadClients := settings["clients"]
  171. mutated := hadClients || len(finalClients) > 0
  172. if mutated {
  173. settings["clients"] = finalClients
  174. }
  175. if inboundCanHostFallbacks(inbound) {
  176. fallbacks, fbErr := s.inboundService.fallbackService.BuildFallbacksJSON(nil, inbound.Id)
  177. if fbErr != nil {
  178. return nil, fbErr
  179. }
  180. if len(fallbacks) > 0 {
  181. generic := make([]any, 0, len(fallbacks))
  182. for _, f := range fallbacks {
  183. generic = append(generic, f)
  184. }
  185. settings["fallbacks"] = generic
  186. mutated = true
  187. }
  188. }
  189. if mutated {
  190. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  191. if err != nil {
  192. return nil, err
  193. }
  194. inbound.Settings = string(modifiedSettings)
  195. }
  196. if len(inbound.StreamSettings) > 0 {
  197. // Unmarshal stream JSON
  198. var stream map[string]any
  199. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  200. // Remove the "settings" field under "tlsSettings" and "realitySettings"
  201. tlsSettings, ok1 := stream["tlsSettings"].(map[string]any)
  202. realitySettings, ok2 := stream["realitySettings"].(map[string]any)
  203. if ok1 || ok2 {
  204. if ok1 {
  205. delete(tlsSettings, "settings")
  206. } else if ok2 {
  207. delete(realitySettings, "settings")
  208. }
  209. }
  210. delete(stream, "externalProxy")
  211. newStream, err := json.MarshalIndent(stream, "", " ")
  212. if err != nil {
  213. return nil, err
  214. }
  215. inbound.StreamSettings = string(newStream)
  216. }
  217. if inbound.Protocol == model.Shadowsocks {
  218. if healed, ok := model.HealShadowsocksClientMethods(inbound.Settings); ok {
  219. inbound.Settings = healed
  220. }
  221. }
  222. inboundConfig := inbound.GenXrayInboundConfig()
  223. xrayConfig.InboundConfigs = append(xrayConfig.InboundConfigs, *inboundConfig)
  224. }
  225. // Merge subscription-derived outbounds (if any) into the final outbounds array.
  226. // These are additive: each subscription is placed before or after the template
  227. // outbounds based on its Prepend flag, ordered by Priority. Tags assigned by the
  228. // subscription service are kept stable across refreshes so that balancers and
  229. // routing rules continue to work.
  230. subSvc := &OutboundSubscriptionService{}
  231. if prepend, appendList, err := subSvc.activeOutboundsSplit(); err == nil && (len(prepend) > 0 || len(appendList) > 0) {
  232. mergeSubscriptionOutbounds(xrayConfig, prepend, appendList)
  233. }
  234. return xrayConfig, nil
  235. }
  236. // mergeSubscriptionOutbounds appends the subscription outbounds to the
  237. // OutboundConfigs array of the xray config. It works on the already-unmarshaled
  238. // template so that manually configured outbounds are never overwritten.
  239. //
  240. // Safety: if we cannot parse the template's outbounds array, we leave
  241. // OutboundConfigs exactly as it came from the template (we do not inject
  242. // subscription outbounds). This prevents us from accidentally dropping the
  243. // user's manually configured outbounds when the template is in a weird state.
  244. func mergeSubscriptionOutbounds(cfg *xray.Config, prepend, appendList []any) {
  245. if len(prepend) == 0 && len(appendList) == 0 {
  246. return
  247. }
  248. var templateOutbounds []any
  249. if len(cfg.OutboundConfigs) > 0 {
  250. if err := json.Unmarshal(cfg.OutboundConfigs, &templateOutbounds); err != nil {
  251. // Corrupt template outbounds — do not touch the field at all.
  252. // The user will see problems on Xray start / next save.
  253. return
  254. }
  255. }
  256. merged := make([]any, 0, len(prepend)+len(templateOutbounds)+len(appendList))
  257. merged = append(merged, prepend...)
  258. merged = append(merged, templateOutbounds...)
  259. merged = append(merged, appendList...)
  260. combined, err := json.MarshalIndent(merged, "", " ")
  261. if err != nil {
  262. return
  263. }
  264. cfg.OutboundConfigs = json_util.RawMessage(combined)
  265. }
  266. // resolveXrayLogPaths rewrites relative `log.access` / `log.error` values to
  267. // absolute paths under config.GetLogFolder(), so Xray writes those files
  268. // alongside the panel's other logs regardless of the working directory the
  269. // panel was launched from. Values that are empty, "none", or already absolute
  270. // are left untouched, as are unparseable log blocks.
  271. func resolveXrayLogPaths(logCfg json_util.RawMessage) json_util.RawMessage {
  272. if len(logCfg) == 0 {
  273. return logCfg
  274. }
  275. var parsed map[string]any
  276. if err := json.Unmarshal(logCfg, &parsed); err != nil {
  277. return logCfg
  278. }
  279. changed := false
  280. for _, key := range []string{"access", "error"} {
  281. v, ok := parsed[key].(string)
  282. if !ok {
  283. continue
  284. }
  285. trimmed := strings.TrimSpace(v)
  286. if trimmed == "" || strings.EqualFold(trimmed, "none") {
  287. continue
  288. }
  289. if filepath.IsAbs(trimmed) {
  290. continue
  291. }
  292. cleaned := filepath.ToSlash(filepath.Clean(trimmed))
  293. base := filepath.Base(cleaned)
  294. if base == "" || base == "." || base == string(filepath.Separator) {
  295. continue
  296. }
  297. // Only rewrite bare names ("./access.log", "access.log").
  298. // A nested relative path like "./logs/foo.log" is treated as
  299. // a deliberate user choice and left alone.
  300. if cleaned != base {
  301. continue
  302. }
  303. parsed[key] = filepath.Join(config.GetLogFolder(), base)
  304. changed = true
  305. }
  306. if !changed {
  307. return logCfg
  308. }
  309. out, err := json.Marshal(parsed)
  310. if err != nil {
  311. return logCfg
  312. }
  313. return out
  314. }
  315. // GetXrayTraffic fetches the current traffic statistics from the running Xray process.
  316. func (s *XrayService) GetXrayTraffic() ([]*xray.Traffic, []*xray.ClientTraffic, error) {
  317. if !s.IsXrayRunning() {
  318. err := errors.New("xray is not running")
  319. logger.Debug("Attempted to fetch Xray traffic, but Xray is not running:", err)
  320. return nil, nil, err
  321. }
  322. apiPort := p.GetAPIPort()
  323. if err := s.xrayAPI.Init(apiPort); err != nil {
  324. logger.Debug("Failed to initialize Xray API:", err)
  325. return nil, nil, err
  326. }
  327. defer s.xrayAPI.Close()
  328. traffic, clientTraffic, err := s.xrayAPI.GetTraffic()
  329. if err != nil {
  330. logger.Debug("Failed to fetch Xray traffic:", err)
  331. return nil, nil, err
  332. }
  333. return traffic, clientTraffic, nil
  334. }
  335. // RestartXray restarts the Xray process, optionally forcing a restart even if config unchanged.
  336. func (s *XrayService) RestartXray(isForce bool) error {
  337. lock.Lock()
  338. defer lock.Unlock()
  339. logger.Debug("restart Xray, force:", isForce)
  340. isManuallyStopped.Store(false)
  341. xrayConfig, err := s.GetXrayConfig()
  342. if err != nil {
  343. return err
  344. }
  345. if s.IsXrayRunning() {
  346. if !isForce && p.GetConfig().Equals(xrayConfig) && !isNeedXrayRestart.Load() {
  347. logger.Debug("It does not need to restart Xray")
  348. return nil
  349. }
  350. p.Stop()
  351. }
  352. p = xray.NewProcess(xrayConfig)
  353. result = ""
  354. s.xrayAPI.StatsLastValues = nil
  355. err = p.Start()
  356. if err != nil {
  357. return err
  358. }
  359. return nil
  360. }
  361. // StopXray stops the running Xray process.
  362. func (s *XrayService) StopXray() error {
  363. lock.Lock()
  364. defer lock.Unlock()
  365. isManuallyStopped.Store(true)
  366. logger.Debug("Attempting to stop Xray...")
  367. if s.IsXrayRunning() {
  368. return p.Stop()
  369. }
  370. return errors.New("xray is not running")
  371. }
  372. // SetToNeedRestart marks that Xray needs to be restarted.
  373. func (s *XrayService) SetToNeedRestart() {
  374. isNeedXrayRestart.Store(true)
  375. }
  376. // GetXrayAPIPort returns the port the local xray process is listening on
  377. // for its gRPC HandlerService, or 0 when xray isn't currently running.
  378. // Exposed for the runtime package's LocalRuntime adapter — runtime can't
  379. // reach into the package-level `p` directly without a service-package
  380. // import cycle.
  381. func (s *XrayService) GetXrayAPIPort() int {
  382. if p == nil || !p.IsRunning() {
  383. return 0
  384. }
  385. return p.GetAPIPort()
  386. }
  387. // IsNeedRestartAndSetFalse checks if restart is needed and resets the flag to false.
  388. func (s *XrayService) IsNeedRestartAndSetFalse() bool {
  389. return isNeedXrayRestart.CompareAndSwap(true, false)
  390. }
  391. // DidXrayCrash checks if Xray crashed by verifying it's not running and wasn't manually stopped.
  392. func (s *XrayService) DidXrayCrash() bool {
  393. return !s.IsXrayRunning() && !isManuallyStopped.Load()
  394. }