xray.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. settings := map[string]any{}
  106. json.Unmarshal([]byte(inbound.Settings), &settings)
  107. dbClients, listErr := s.inboundService.clientService.ListForInbound(nil, inbound.Id)
  108. if listErr != nil {
  109. return nil, listErr
  110. }
  111. clientStats := inbound.ClientStats
  112. enableMap := make(map[string]bool, len(clientStats))
  113. for _, clientTraffic := range clientStats {
  114. enableMap[clientTraffic.Email] = clientTraffic.Enable
  115. }
  116. var finalClients []any
  117. for i := range dbClients {
  118. c := dbClients[i]
  119. if enable, exists := enableMap[c.Email]; exists && !enable {
  120. logger.Infof("Remove Inbound User %s due to expiration or traffic limit", c.Email)
  121. continue
  122. }
  123. if !c.Enable {
  124. continue
  125. }
  126. flow := c.Flow
  127. if flow == "xtls-rprx-vision-udp443" {
  128. flow = "xtls-rprx-vision"
  129. }
  130. entry := map[string]any{"email": c.Email}
  131. switch inbound.Protocol {
  132. case model.VLESS:
  133. if c.ID != "" {
  134. entry["id"] = c.ID
  135. }
  136. if flow != "" {
  137. entry["flow"] = flow
  138. }
  139. if c.Reverse != nil {
  140. entry["reverse"] = c.Reverse
  141. }
  142. case model.VMESS:
  143. if c.ID != "" {
  144. entry["id"] = c.ID
  145. }
  146. if c.Security != "" {
  147. entry["security"] = c.Security
  148. }
  149. case model.Trojan:
  150. if c.Password != "" {
  151. entry["password"] = c.Password
  152. }
  153. if flow != "" {
  154. entry["flow"] = flow
  155. }
  156. case model.Shadowsocks:
  157. if c.Password != "" {
  158. entry["password"] = c.Password
  159. }
  160. if c.Security != "" {
  161. entry["method"] = c.Security
  162. }
  163. case model.Hysteria, model.Hysteria2:
  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 := healShadowsocksClientMethods(inbound.Settings); ok {
  219. inbound.Settings = healed
  220. }
  221. }
  222. inboundConfig := inbound.GenXrayInboundConfig()
  223. xrayConfig.InboundConfigs = append(xrayConfig.InboundConfigs, *inboundConfig)
  224. }
  225. return xrayConfig, nil
  226. }
  227. // resolveXrayLogPaths rewrites relative `log.access` / `log.error` values to
  228. // absolute paths under config.GetLogFolder(), so Xray writes those files
  229. // alongside the panel's other logs regardless of the working directory the
  230. // panel was launched from. Values that are empty, "none", or already absolute
  231. // are left untouched, as are unparseable log blocks.
  232. func resolveXrayLogPaths(logCfg json_util.RawMessage) json_util.RawMessage {
  233. if len(logCfg) == 0 {
  234. return logCfg
  235. }
  236. var parsed map[string]any
  237. if err := json.Unmarshal(logCfg, &parsed); err != nil {
  238. return logCfg
  239. }
  240. changed := false
  241. for _, key := range []string{"access", "error"} {
  242. v, ok := parsed[key].(string)
  243. if !ok {
  244. continue
  245. }
  246. trimmed := strings.TrimSpace(v)
  247. if trimmed == "" || strings.EqualFold(trimmed, "none") {
  248. continue
  249. }
  250. if filepath.IsAbs(trimmed) {
  251. continue
  252. }
  253. cleaned := filepath.ToSlash(filepath.Clean(trimmed))
  254. base := filepath.Base(cleaned)
  255. if base == "" || base == "." || base == string(filepath.Separator) {
  256. continue
  257. }
  258. // Only rewrite bare names ("./access.log", "access.log").
  259. // A nested relative path like "./logs/foo.log" is treated as
  260. // a deliberate user choice and left alone.
  261. if cleaned != base {
  262. continue
  263. }
  264. parsed[key] = filepath.Join(config.GetLogFolder(), base)
  265. changed = true
  266. }
  267. if !changed {
  268. return logCfg
  269. }
  270. out, err := json.Marshal(parsed)
  271. if err != nil {
  272. return logCfg
  273. }
  274. return out
  275. }
  276. // healShadowsocksClientMethods is the same idea as applyShadowsocksClientMethod
  277. // (see client.go) but applied at xray-config-build time, to backfill the
  278. // per-client method field for legacy shadowsocks inbounds whose clients were
  279. // stored before applyShadowsocksClientMethod existed. Returns the rewritten
  280. // settings string and true when anything actually changed.
  281. func healShadowsocksClientMethods(settings string) (string, bool) {
  282. if settings == "" {
  283. return settings, false
  284. }
  285. var parsed map[string]any
  286. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  287. return settings, false
  288. }
  289. method, _ := parsed["method"].(string)
  290. if method == "" || strings.HasPrefix(method, "2022-blake3-") {
  291. return settings, false
  292. }
  293. clients, ok := parsed["clients"].([]any)
  294. if !ok {
  295. return settings, false
  296. }
  297. changed := false
  298. for i := range clients {
  299. cm, ok := clients[i].(map[string]any)
  300. if !ok {
  301. continue
  302. }
  303. if existing, _ := cm["method"].(string); existing != "" {
  304. continue
  305. }
  306. cm["method"] = method
  307. clients[i] = cm
  308. changed = true
  309. }
  310. if !changed {
  311. return settings, false
  312. }
  313. out, err := json.MarshalIndent(parsed, "", " ")
  314. if err != nil {
  315. return settings, false
  316. }
  317. return string(out), true
  318. }
  319. // GetXrayTraffic fetches the current traffic statistics from the running Xray process.
  320. func (s *XrayService) GetXrayTraffic() ([]*xray.Traffic, []*xray.ClientTraffic, error) {
  321. if !s.IsXrayRunning() {
  322. err := errors.New("xray is not running")
  323. logger.Debug("Attempted to fetch Xray traffic, but Xray is not running:", err)
  324. return nil, nil, err
  325. }
  326. apiPort := p.GetAPIPort()
  327. if err := s.xrayAPI.Init(apiPort); err != nil {
  328. logger.Debug("Failed to initialize Xray API:", err)
  329. return nil, nil, err
  330. }
  331. defer s.xrayAPI.Close()
  332. traffic, clientTraffic, err := s.xrayAPI.GetTraffic()
  333. if err != nil {
  334. logger.Debug("Failed to fetch Xray traffic:", err)
  335. return nil, nil, err
  336. }
  337. return traffic, clientTraffic, nil
  338. }
  339. // RestartXray restarts the Xray process, optionally forcing a restart even if config unchanged.
  340. func (s *XrayService) RestartXray(isForce bool) error {
  341. lock.Lock()
  342. defer lock.Unlock()
  343. logger.Debug("restart Xray, force:", isForce)
  344. isManuallyStopped.Store(false)
  345. xrayConfig, err := s.GetXrayConfig()
  346. if err != nil {
  347. return err
  348. }
  349. if s.IsXrayRunning() {
  350. if !isForce && p.GetConfig().Equals(xrayConfig) && !isNeedXrayRestart.Load() {
  351. logger.Debug("It does not need to restart Xray")
  352. return nil
  353. }
  354. p.Stop()
  355. }
  356. p = xray.NewProcess(xrayConfig)
  357. result = ""
  358. s.xrayAPI.StatsLastValues = nil
  359. err = p.Start()
  360. if err != nil {
  361. return err
  362. }
  363. return nil
  364. }
  365. // StopXray stops the running Xray process.
  366. func (s *XrayService) StopXray() error {
  367. lock.Lock()
  368. defer lock.Unlock()
  369. isManuallyStopped.Store(true)
  370. logger.Debug("Attempting to stop Xray...")
  371. if s.IsXrayRunning() {
  372. return p.Stop()
  373. }
  374. return errors.New("xray is not running")
  375. }
  376. // SetToNeedRestart marks that Xray needs to be restarted.
  377. func (s *XrayService) SetToNeedRestart() {
  378. isNeedXrayRestart.Store(true)
  379. }
  380. // GetXrayAPIPort returns the port the local xray process is listening on
  381. // for its gRPC HandlerService, or 0 when xray isn't currently running.
  382. // Exposed for the runtime package's LocalRuntime adapter — runtime can't
  383. // reach into the package-level `p` directly without a service-package
  384. // import cycle.
  385. func (s *XrayService) GetXrayAPIPort() int {
  386. if p == nil || !p.IsRunning() {
  387. return 0
  388. }
  389. return p.GetAPIPort()
  390. }
  391. // IsNeedRestartAndSetFalse checks if restart is needed and resets the flag to false.
  392. func (s *XrayService) IsNeedRestartAndSetFalse() bool {
  393. return isNeedXrayRestart.CompareAndSwap(true, false)
  394. }
  395. // DidXrayCrash checks if Xray crashed by verifying it's not running and wasn't manually stopped.
  396. func (s *XrayService) DidXrayCrash() bool {
  397. return !s.IsXrayRunning() && !isManuallyStopped.Load()
  398. }