xray.go 12 KB

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