server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. package service
  2. import (
  3. "archive/zip"
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "io/fs"
  9. "mime/multipart"
  10. "net/http"
  11. "os"
  12. "os/exec"
  13. "runtime"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "x-ui/config"
  18. "x-ui/database"
  19. "x-ui/logger"
  20. "x-ui/util/common"
  21. "x-ui/util/sys"
  22. "x-ui/xray"
  23. "github.com/shirou/gopsutil/v4/cpu"
  24. "github.com/shirou/gopsutil/v4/disk"
  25. "github.com/shirou/gopsutil/v4/host"
  26. "github.com/shirou/gopsutil/v4/load"
  27. "github.com/shirou/gopsutil/v4/mem"
  28. "github.com/shirou/gopsutil/v4/net"
  29. )
  30. type ProcessState string
  31. const (
  32. Running ProcessState = "running"
  33. Stop ProcessState = "stop"
  34. Error ProcessState = "error"
  35. )
  36. type Status struct {
  37. T time.Time `json:"-"`
  38. Cpu float64 `json:"cpu"`
  39. CpuCores int `json:"cpuCores"`
  40. LogicalPro int `json:"logicalPro"`
  41. CpuSpeedMhz float64 `json:"cpuSpeedMhz"`
  42. Mem struct {
  43. Current uint64 `json:"current"`
  44. Total uint64 `json:"total"`
  45. } `json:"mem"`
  46. Swap struct {
  47. Current uint64 `json:"current"`
  48. Total uint64 `json:"total"`
  49. } `json:"swap"`
  50. Disk struct {
  51. Current uint64 `json:"current"`
  52. Total uint64 `json:"total"`
  53. } `json:"disk"`
  54. Xray struct {
  55. State ProcessState `json:"state"`
  56. ErrorMsg string `json:"errorMsg"`
  57. Version string `json:"version"`
  58. } `json:"xray"`
  59. Uptime uint64 `json:"uptime"`
  60. Loads []float64 `json:"loads"`
  61. TcpCount int `json:"tcpCount"`
  62. UdpCount int `json:"udpCount"`
  63. NetIO struct {
  64. Up uint64 `json:"up"`
  65. Down uint64 `json:"down"`
  66. } `json:"netIO"`
  67. NetTraffic struct {
  68. Sent uint64 `json:"sent"`
  69. Recv uint64 `json:"recv"`
  70. } `json:"netTraffic"`
  71. PublicIP struct {
  72. IPv4 string `json:"ipv4"`
  73. IPv6 string `json:"ipv6"`
  74. } `json:"publicIP"`
  75. AppStats struct {
  76. Threads uint32 `json:"threads"`
  77. Mem uint64 `json:"mem"`
  78. Uptime uint64 `json:"uptime"`
  79. } `json:"appStats"`
  80. }
  81. type Release struct {
  82. TagName string `json:"tag_name"`
  83. }
  84. type ServerService struct {
  85. xrayService XrayService
  86. inboundService InboundService
  87. }
  88. func getPublicIP(url string) string {
  89. resp, err := http.Get(url)
  90. if err != nil {
  91. return "N/A"
  92. }
  93. defer resp.Body.Close()
  94. ip, err := io.ReadAll(resp.Body)
  95. if err != nil {
  96. return "N/A"
  97. }
  98. ipString := string(ip)
  99. if ipString == "" {
  100. return "N/A"
  101. }
  102. return ipString
  103. }
  104. func (s *ServerService) GetStatus(lastStatus *Status) *Status {
  105. now := time.Now()
  106. status := &Status{
  107. T: now,
  108. }
  109. percents, err := cpu.Percent(0, false)
  110. if err != nil {
  111. logger.Warning("get cpu percent failed:", err)
  112. } else {
  113. status.Cpu = percents[0]
  114. }
  115. status.CpuCores, err = cpu.Counts(false)
  116. if err != nil {
  117. logger.Warning("get cpu cores count failed:", err)
  118. }
  119. status.LogicalPro = runtime.NumCPU()
  120. if p != nil && p.IsRunning() {
  121. status.AppStats.Uptime = p.GetUptime()
  122. } else {
  123. status.AppStats.Uptime = 0
  124. }
  125. cpuInfos, err := cpu.Info()
  126. if err != nil {
  127. logger.Warning("get cpu info failed:", err)
  128. } else if len(cpuInfos) > 0 {
  129. cpuInfo := cpuInfos[0]
  130. status.CpuSpeedMhz = cpuInfo.Mhz // setting CPU speed in MHz
  131. } else {
  132. logger.Warning("could not find cpu info")
  133. }
  134. upTime, err := host.Uptime()
  135. if err != nil {
  136. logger.Warning("get uptime failed:", err)
  137. } else {
  138. status.Uptime = upTime
  139. }
  140. memInfo, err := mem.VirtualMemory()
  141. if err != nil {
  142. logger.Warning("get virtual memory failed:", err)
  143. } else {
  144. status.Mem.Current = memInfo.Used
  145. status.Mem.Total = memInfo.Total
  146. }
  147. swapInfo, err := mem.SwapMemory()
  148. if err != nil {
  149. logger.Warning("get swap memory failed:", err)
  150. } else {
  151. status.Swap.Current = swapInfo.Used
  152. status.Swap.Total = swapInfo.Total
  153. }
  154. distInfo, err := disk.Usage("/")
  155. if err != nil {
  156. logger.Warning("get dist usage failed:", err)
  157. } else {
  158. status.Disk.Current = distInfo.Used
  159. status.Disk.Total = distInfo.Total
  160. }
  161. avgState, err := load.Avg()
  162. if err != nil {
  163. logger.Warning("get load avg failed:", err)
  164. } else {
  165. status.Loads = []float64{avgState.Load1, avgState.Load5, avgState.Load15}
  166. }
  167. ioStats, err := net.IOCounters(false)
  168. if err != nil {
  169. logger.Warning("get io counters failed:", err)
  170. } else if len(ioStats) > 0 {
  171. ioStat := ioStats[0]
  172. status.NetTraffic.Sent = ioStat.BytesSent
  173. status.NetTraffic.Recv = ioStat.BytesRecv
  174. if lastStatus != nil {
  175. duration := now.Sub(lastStatus.T)
  176. seconds := float64(duration) / float64(time.Second)
  177. up := uint64(float64(status.NetTraffic.Sent-lastStatus.NetTraffic.Sent) / seconds)
  178. down := uint64(float64(status.NetTraffic.Recv-lastStatus.NetTraffic.Recv) / seconds)
  179. status.NetIO.Up = up
  180. status.NetIO.Down = down
  181. }
  182. } else {
  183. logger.Warning("can not find io counters")
  184. }
  185. status.TcpCount, err = sys.GetTCPCount()
  186. if err != nil {
  187. logger.Warning("get tcp connections failed:", err)
  188. }
  189. status.UdpCount, err = sys.GetUDPCount()
  190. if err != nil {
  191. logger.Warning("get udp connections failed:", err)
  192. }
  193. status.PublicIP.IPv4 = getPublicIP("https://api.ipify.org")
  194. status.PublicIP.IPv6 = getPublicIP("https://api6.ipify.org")
  195. if s.xrayService.IsXrayRunning() {
  196. status.Xray.State = Running
  197. status.Xray.ErrorMsg = ""
  198. } else {
  199. err := s.xrayService.GetXrayErr()
  200. if err != nil {
  201. status.Xray.State = Error
  202. } else {
  203. status.Xray.State = Stop
  204. }
  205. status.Xray.ErrorMsg = s.xrayService.GetXrayResult()
  206. }
  207. status.Xray.Version = s.xrayService.GetXrayVersion()
  208. var rtm runtime.MemStats
  209. runtime.ReadMemStats(&rtm)
  210. status.AppStats.Mem = rtm.Sys
  211. status.AppStats.Threads = uint32(runtime.NumGoroutine())
  212. if p != nil && p.IsRunning() {
  213. status.AppStats.Uptime = p.GetUptime()
  214. } else {
  215. status.AppStats.Uptime = 0
  216. }
  217. return status
  218. }
  219. func (s *ServerService) GetXrayVersions() ([]string, error) {
  220. url := "https://api.github.com/repos/XTLS/Xray-core/releases"
  221. resp, err := http.Get(url)
  222. if err != nil {
  223. return nil, err
  224. }
  225. defer resp.Body.Close()
  226. buffer := bytes.NewBuffer(make([]byte, 8192))
  227. buffer.Reset()
  228. _, err = buffer.ReadFrom(resp.Body)
  229. if err != nil {
  230. return nil, err
  231. }
  232. releases := make([]Release, 0)
  233. err = json.Unmarshal(buffer.Bytes(), &releases)
  234. if err != nil {
  235. return nil, err
  236. }
  237. var versions []string
  238. for _, release := range releases {
  239. if release.TagName >= "v1.7.5" {
  240. versions = append(versions, release.TagName)
  241. }
  242. }
  243. return versions, nil
  244. }
  245. func (s *ServerService) StopXrayService() (string error) {
  246. err := s.xrayService.StopXray()
  247. if err != nil {
  248. logger.Error("stop xray failed:", err)
  249. return err
  250. }
  251. return nil
  252. }
  253. func (s *ServerService) RestartXrayService() (string error) {
  254. s.xrayService.StopXray()
  255. defer func() {
  256. err := s.xrayService.RestartXray(true)
  257. if err != nil {
  258. logger.Error("start xray failed:", err)
  259. }
  260. }()
  261. return nil
  262. }
  263. func (s *ServerService) downloadXRay(version string) (string, error) {
  264. osName := runtime.GOOS
  265. arch := runtime.GOARCH
  266. switch osName {
  267. case "darwin":
  268. osName = "macos"
  269. }
  270. switch arch {
  271. case "amd64":
  272. arch = "64"
  273. case "arm64":
  274. arch = "arm64-v8a"
  275. }
  276. fileName := fmt.Sprintf("Xray-%s-%s.zip", osName, arch)
  277. url := fmt.Sprintf("https://github.com/XTLS/Xray-core/releases/download/%s/%s", version, fileName)
  278. resp, err := http.Get(url)
  279. if err != nil {
  280. return "", err
  281. }
  282. defer resp.Body.Close()
  283. os.Remove(fileName)
  284. file, err := os.Create(fileName)
  285. if err != nil {
  286. return "", err
  287. }
  288. defer file.Close()
  289. _, err = io.Copy(file, resp.Body)
  290. if err != nil {
  291. return "", err
  292. }
  293. return fileName, nil
  294. }
  295. func (s *ServerService) UpdateXray(version string) error {
  296. zipFileName, err := s.downloadXRay(version)
  297. if err != nil {
  298. return err
  299. }
  300. zipFile, err := os.Open(zipFileName)
  301. if err != nil {
  302. return err
  303. }
  304. defer func() {
  305. zipFile.Close()
  306. os.Remove(zipFileName)
  307. }()
  308. stat, err := zipFile.Stat()
  309. if err != nil {
  310. return err
  311. }
  312. reader, err := zip.NewReader(zipFile, stat.Size())
  313. if err != nil {
  314. return err
  315. }
  316. s.xrayService.StopXray()
  317. defer func() {
  318. err := s.xrayService.RestartXray(true)
  319. if err != nil {
  320. logger.Error("start xray failed:", err)
  321. }
  322. }()
  323. copyZipFile := func(zipName string, fileName string) error {
  324. zipFile, err := reader.Open(zipName)
  325. if err != nil {
  326. return err
  327. }
  328. os.Remove(fileName)
  329. file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, fs.ModePerm)
  330. if err != nil {
  331. return err
  332. }
  333. defer file.Close()
  334. _, err = io.Copy(file, zipFile)
  335. return err
  336. }
  337. err = copyZipFile("xray", xray.GetBinaryPath())
  338. if err != nil {
  339. return err
  340. }
  341. return nil
  342. }
  343. func (s *ServerService) GetLogs(count string, level string, syslog string) []string {
  344. c, _ := strconv.Atoi(count)
  345. var lines []string
  346. if syslog == "true" {
  347. cmdArgs := []string{"journalctl", "-u", "x-ui", "--no-pager", "-n", count, "-p", level}
  348. // Run the command
  349. cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
  350. var out bytes.Buffer
  351. cmd.Stdout = &out
  352. err := cmd.Run()
  353. if err != nil {
  354. return []string{"Failed to run journalctl command!"}
  355. }
  356. lines = strings.Split(out.String(), "\n")
  357. } else {
  358. lines = logger.GetLogs(c, level)
  359. }
  360. return lines
  361. }
  362. func (s *ServerService) GetConfigJson() (interface{}, error) {
  363. config, err := s.xrayService.GetXrayConfig()
  364. if err != nil {
  365. return nil, err
  366. }
  367. contents, err := json.MarshalIndent(config, "", " ")
  368. if err != nil {
  369. return nil, err
  370. }
  371. var jsonData interface{}
  372. err = json.Unmarshal(contents, &jsonData)
  373. if err != nil {
  374. return nil, err
  375. }
  376. return jsonData, nil
  377. }
  378. func (s *ServerService) GetDb() ([]byte, error) {
  379. // Update by manually trigger a checkpoint operation
  380. err := database.Checkpoint()
  381. if err != nil {
  382. return nil, err
  383. }
  384. // Open the file for reading
  385. file, err := os.Open(config.GetDBPath())
  386. if err != nil {
  387. return nil, err
  388. }
  389. defer file.Close()
  390. // Read the file contents
  391. fileContents, err := io.ReadAll(file)
  392. if err != nil {
  393. return nil, err
  394. }
  395. return fileContents, nil
  396. }
  397. func (s *ServerService) ImportDB(file multipart.File) error {
  398. // Check if the file is a SQLite database
  399. isValidDb, err := database.IsSQLiteDB(file)
  400. if err != nil {
  401. return common.NewErrorf("Error checking db file format: %v", err)
  402. }
  403. if !isValidDb {
  404. return common.NewError("Invalid db file format")
  405. }
  406. // Reset the file reader to the beginning
  407. _, err = file.Seek(0, 0)
  408. if err != nil {
  409. return common.NewErrorf("Error resetting file reader: %v", err)
  410. }
  411. // Save the file as temporary file
  412. tempPath := fmt.Sprintf("%s.temp", config.GetDBPath())
  413. // Remove the existing fallback file (if any) before creating one
  414. _, err = os.Stat(tempPath)
  415. if err == nil {
  416. errRemove := os.Remove(tempPath)
  417. if errRemove != nil {
  418. return common.NewErrorf("Error removing existing temporary db file: %v", errRemove)
  419. }
  420. }
  421. // Create the temporary file
  422. tempFile, err := os.Create(tempPath)
  423. if err != nil {
  424. return common.NewErrorf("Error creating temporary db file: %v", err)
  425. }
  426. defer tempFile.Close()
  427. // Remove temp file before returning
  428. defer os.Remove(tempPath)
  429. // Save uploaded file to temporary file
  430. _, err = io.Copy(tempFile, file)
  431. if err != nil {
  432. return common.NewErrorf("Error saving db: %v", err)
  433. }
  434. // Check if we can init db or not
  435. err = database.InitDB(tempPath)
  436. if err != nil {
  437. return common.NewErrorf("Error checking db: %v", err)
  438. }
  439. // Stop Xray
  440. s.StopXrayService()
  441. // Backup the current database for fallback
  442. fallbackPath := fmt.Sprintf("%s.backup", config.GetDBPath())
  443. // Remove the existing fallback file (if any)
  444. _, err = os.Stat(fallbackPath)
  445. if err == nil {
  446. errRemove := os.Remove(fallbackPath)
  447. if errRemove != nil {
  448. return common.NewErrorf("Error removing existing fallback db file: %v", errRemove)
  449. }
  450. }
  451. // Move the current database to the fallback location
  452. err = os.Rename(config.GetDBPath(), fallbackPath)
  453. if err != nil {
  454. return common.NewErrorf("Error backing up temporary db file: %v", err)
  455. }
  456. // Remove the temporary file before returning
  457. defer os.Remove(fallbackPath)
  458. // Move temp to DB path
  459. err = os.Rename(tempPath, config.GetDBPath())
  460. if err != nil {
  461. errRename := os.Rename(fallbackPath, config.GetDBPath())
  462. if errRename != nil {
  463. return common.NewErrorf("Error moving db file and restoring fallback: %v", errRename)
  464. }
  465. return common.NewErrorf("Error moving db file: %v", err)
  466. }
  467. // Migrate DB
  468. err = database.InitDB(config.GetDBPath())
  469. if err != nil {
  470. errRename := os.Rename(fallbackPath, config.GetDBPath())
  471. if errRename != nil {
  472. return common.NewErrorf("Error migrating db and restoring fallback: %v", errRename)
  473. }
  474. return common.NewErrorf("Error migrating db: %v", err)
  475. }
  476. s.inboundService.MigrateDB()
  477. // Start Xray
  478. err = s.RestartXrayService()
  479. if err != nil {
  480. return common.NewErrorf("Imported DB but Failed to start Xray: %v", err)
  481. }
  482. return nil
  483. }
  484. func (s *ServerService) GetNewX25519Cert() (interface{}, error) {
  485. // Run the command
  486. cmd := exec.Command(xray.GetBinaryPath(), "x25519")
  487. var out bytes.Buffer
  488. cmd.Stdout = &out
  489. err := cmd.Run()
  490. if err != nil {
  491. return nil, err
  492. }
  493. lines := strings.Split(out.String(), "\n")
  494. privateKeyLine := strings.Split(lines[0], ":")
  495. publicKeyLine := strings.Split(lines[1], ":")
  496. privateKey := strings.TrimSpace(privateKeyLine[1])
  497. publicKey := strings.TrimSpace(publicKeyLine[1])
  498. keyPair := map[string]interface{}{
  499. "privateKey": privateKey,
  500. "publicKey": publicKey,
  501. }
  502. return keyPair, nil
  503. }