1
0

xray.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. case model.Hysteria:
  161. if c.Auth != "" {
  162. entry["auth"] = c.Auth
  163. }
  164. }
  165. finalClients = append(finalClients, entry)
  166. }
  167. _, hadClients := settings["clients"]
  168. mutated := hadClients || len(finalClients) > 0
  169. if mutated {
  170. settings["clients"] = finalClients
  171. }
  172. if inboundCanHostFallbacks(inbound) {
  173. fallbacks, fbErr := s.inboundService.fallbackService.BuildFallbacksJSON(nil, inbound.Id)
  174. if fbErr != nil {
  175. return nil, fbErr
  176. }
  177. if len(fallbacks) > 0 {
  178. generic := make([]any, 0, len(fallbacks))
  179. for _, f := range fallbacks {
  180. generic = append(generic, f)
  181. }
  182. settings["fallbacks"] = generic
  183. mutated = true
  184. }
  185. }
  186. if mutated {
  187. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  188. if err != nil {
  189. return nil, err
  190. }
  191. inbound.Settings = string(modifiedSettings)
  192. }
  193. if len(inbound.StreamSettings) > 0 {
  194. // Unmarshal stream JSON
  195. var stream map[string]any
  196. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  197. // Remove the "settings" field under "tlsSettings" and "realitySettings"
  198. tlsSettings, ok1 := stream["tlsSettings"].(map[string]any)
  199. realitySettings, ok2 := stream["realitySettings"].(map[string]any)
  200. if ok1 || ok2 {
  201. if ok1 {
  202. delete(tlsSettings, "settings")
  203. } else if ok2 {
  204. delete(realitySettings, "settings")
  205. }
  206. }
  207. delete(stream, "externalProxy")
  208. newStream, err := json.MarshalIndent(stream, "", " ")
  209. if err != nil {
  210. return nil, err
  211. }
  212. inbound.StreamSettings = string(newStream)
  213. }
  214. if inbound.Protocol == model.Shadowsocks {
  215. if healed, ok := model.HealShadowsocksClientMethods(inbound.Settings); ok {
  216. inbound.Settings = healed
  217. }
  218. }
  219. inboundConfig := inbound.GenXrayInboundConfig()
  220. xrayConfig.InboundConfigs = append(xrayConfig.InboundConfigs, *inboundConfig)
  221. }
  222. return xrayConfig, nil
  223. }
  224. // resolveXrayLogPaths rewrites relative `log.access` / `log.error` values to
  225. // absolute paths under config.GetLogFolder(), so Xray writes those files
  226. // alongside the panel's other logs regardless of the working directory the
  227. // panel was launched from. Values that are empty, "none", or already absolute
  228. // are left untouched, as are unparseable log blocks.
  229. func resolveXrayLogPaths(logCfg json_util.RawMessage) json_util.RawMessage {
  230. if len(logCfg) == 0 {
  231. return logCfg
  232. }
  233. var parsed map[string]any
  234. if err := json.Unmarshal(logCfg, &parsed); err != nil {
  235. return logCfg
  236. }
  237. changed := false
  238. for _, key := range []string{"access", "error"} {
  239. v, ok := parsed[key].(string)
  240. if !ok {
  241. continue
  242. }
  243. trimmed := strings.TrimSpace(v)
  244. if trimmed == "" || strings.EqualFold(trimmed, "none") {
  245. continue
  246. }
  247. if filepath.IsAbs(trimmed) {
  248. continue
  249. }
  250. cleaned := filepath.ToSlash(filepath.Clean(trimmed))
  251. base := filepath.Base(cleaned)
  252. if base == "" || base == "." || base == string(filepath.Separator) {
  253. continue
  254. }
  255. // Only rewrite bare names ("./access.log", "access.log").
  256. // A nested relative path like "./logs/foo.log" is treated as
  257. // a deliberate user choice and left alone.
  258. if cleaned != base {
  259. continue
  260. }
  261. parsed[key] = filepath.Join(config.GetLogFolder(), base)
  262. changed = true
  263. }
  264. if !changed {
  265. return logCfg
  266. }
  267. out, err := json.Marshal(parsed)
  268. if err != nil {
  269. return logCfg
  270. }
  271. return out
  272. }
  273. // GetXrayTraffic fetches the current traffic statistics from the running Xray process.
  274. func (s *XrayService) GetXrayTraffic() ([]*xray.Traffic, []*xray.ClientTraffic, error) {
  275. if !s.IsXrayRunning() {
  276. err := errors.New("xray is not running")
  277. logger.Debug("Attempted to fetch Xray traffic, but Xray is not running:", err)
  278. return nil, nil, err
  279. }
  280. apiPort := p.GetAPIPort()
  281. if err := s.xrayAPI.Init(apiPort); err != nil {
  282. logger.Debug("Failed to initialize Xray API:", err)
  283. return nil, nil, err
  284. }
  285. defer s.xrayAPI.Close()
  286. traffic, clientTraffic, err := s.xrayAPI.GetTraffic()
  287. if err != nil {
  288. logger.Debug("Failed to fetch Xray traffic:", err)
  289. return nil, nil, err
  290. }
  291. return traffic, clientTraffic, nil
  292. }
  293. // RestartXray restarts the Xray process, optionally forcing a restart even if config unchanged.
  294. func (s *XrayService) RestartXray(isForce bool) error {
  295. lock.Lock()
  296. defer lock.Unlock()
  297. logger.Debug("restart Xray, force:", isForce)
  298. isManuallyStopped.Store(false)
  299. xrayConfig, err := s.GetXrayConfig()
  300. if err != nil {
  301. return err
  302. }
  303. if s.IsXrayRunning() {
  304. if !isForce && p.GetConfig().Equals(xrayConfig) && !isNeedXrayRestart.Load() {
  305. logger.Debug("It does not need to restart Xray")
  306. return nil
  307. }
  308. p.Stop()
  309. }
  310. p = xray.NewProcess(xrayConfig)
  311. result = ""
  312. s.xrayAPI.StatsLastValues = nil
  313. err = p.Start()
  314. if err != nil {
  315. return err
  316. }
  317. return nil
  318. }
  319. // StopXray stops the running Xray process.
  320. func (s *XrayService) StopXray() error {
  321. lock.Lock()
  322. defer lock.Unlock()
  323. isManuallyStopped.Store(true)
  324. logger.Debug("Attempting to stop Xray...")
  325. if s.IsXrayRunning() {
  326. return p.Stop()
  327. }
  328. return errors.New("xray is not running")
  329. }
  330. // SetToNeedRestart marks that Xray needs to be restarted.
  331. func (s *XrayService) SetToNeedRestart() {
  332. isNeedXrayRestart.Store(true)
  333. }
  334. // GetXrayAPIPort returns the port the local xray process is listening on
  335. // for its gRPC HandlerService, or 0 when xray isn't currently running.
  336. // Exposed for the runtime package's LocalRuntime adapter — runtime can't
  337. // reach into the package-level `p` directly without a service-package
  338. // import cycle.
  339. func (s *XrayService) GetXrayAPIPort() int {
  340. if p == nil || !p.IsRunning() {
  341. return 0
  342. }
  343. return p.GetAPIPort()
  344. }
  345. // IsNeedRestartAndSetFalse checks if restart is needed and resets the flag to false.
  346. func (s *XrayService) IsNeedRestartAndSetFalse() bool {
  347. return isNeedXrayRestart.CompareAndSwap(true, false)
  348. }
  349. // DidXrayCrash checks if Xray crashed by verifying it's not running and wasn't manually stopped.
  350. func (s *XrayService) DidXrayCrash() bool {
  351. return !s.IsXrayRunning() && !isManuallyStopped.Load()
  352. }