server.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. const (
  221. XrayURL = "https://api.github.com/repos/XTLS/Xray-core/releases"
  222. bufferSize = 8192
  223. )
  224. resp, err := http.Get(XrayURL)
  225. if err != nil {
  226. return nil, err
  227. }
  228. defer resp.Body.Close()
  229. buffer := bytes.NewBuffer(make([]byte, bufferSize))
  230. buffer.Reset()
  231. if _, err := buffer.ReadFrom(resp.Body); err != nil {
  232. return nil, err
  233. }
  234. var releases []Release
  235. if err := json.Unmarshal(buffer.Bytes(), &releases); err != nil {
  236. return nil, err
  237. }
  238. var versions []string
  239. for _, release := range releases {
  240. tagVersion := strings.TrimPrefix(release.TagName, "v")
  241. tagParts := strings.Split(tagVersion, ".")
  242. if len(tagParts) != 3 {
  243. continue
  244. }
  245. major, err1 := strconv.Atoi(tagParts[0])
  246. minor, err2 := strconv.Atoi(tagParts[1])
  247. patch, err3 := strconv.Atoi(tagParts[2])
  248. if err1 != nil || err2 != nil || err3 != nil {
  249. continue
  250. }
  251. if (major == 1 && minor == 8 && patch == 24) ||
  252. (major == 24 && ((minor > 10) || (minor == 10 && patch >= 16))) ||
  253. (major > 24) {
  254. versions = append(versions, release.TagName)
  255. }
  256. }
  257. return versions, nil
  258. }
  259. func (s *ServerService) StopXrayService() (string error) {
  260. err := s.xrayService.StopXray()
  261. if err != nil {
  262. logger.Error("stop xray failed:", err)
  263. return err
  264. }
  265. return nil
  266. }
  267. func (s *ServerService) RestartXrayService() (string error) {
  268. s.xrayService.StopXray()
  269. defer func() {
  270. err := s.xrayService.RestartXray(true)
  271. if err != nil {
  272. logger.Error("start xray failed:", err)
  273. }
  274. }()
  275. return nil
  276. }
  277. func (s *ServerService) downloadXRay(version string) (string, error) {
  278. osName := runtime.GOOS
  279. arch := runtime.GOARCH
  280. switch osName {
  281. case "darwin":
  282. osName = "macos"
  283. }
  284. switch arch {
  285. case "amd64":
  286. arch = "64"
  287. case "arm64":
  288. arch = "arm64-v8a"
  289. case "armv7":
  290. arch = "arm32-v7a"
  291. case "armv6":
  292. arch = "arm32-v6"
  293. case "armv5":
  294. arch = "arm32-v5"
  295. case "386":
  296. arch = "32"
  297. case "s390x":
  298. arch = "s390x"
  299. }
  300. fileName := fmt.Sprintf("Xray-%s-%s.zip", osName, arch)
  301. url := fmt.Sprintf("https://github.com/XTLS/Xray-core/releases/download/%s/%s", version, fileName)
  302. resp, err := http.Get(url)
  303. if err != nil {
  304. return "", err
  305. }
  306. defer resp.Body.Close()
  307. os.Remove(fileName)
  308. file, err := os.Create(fileName)
  309. if err != nil {
  310. return "", err
  311. }
  312. defer file.Close()
  313. _, err = io.Copy(file, resp.Body)
  314. if err != nil {
  315. return "", err
  316. }
  317. return fileName, nil
  318. }
  319. func (s *ServerService) UpdateXray(version string) error {
  320. zipFileName, err := s.downloadXRay(version)
  321. if err != nil {
  322. return err
  323. }
  324. zipFile, err := os.Open(zipFileName)
  325. if err != nil {
  326. return err
  327. }
  328. defer func() {
  329. zipFile.Close()
  330. os.Remove(zipFileName)
  331. }()
  332. stat, err := zipFile.Stat()
  333. if err != nil {
  334. return err
  335. }
  336. reader, err := zip.NewReader(zipFile, stat.Size())
  337. if err != nil {
  338. return err
  339. }
  340. s.xrayService.StopXray()
  341. defer func() {
  342. err := s.xrayService.RestartXray(true)
  343. if err != nil {
  344. logger.Error("start xray failed:", err)
  345. }
  346. }()
  347. copyZipFile := func(zipName string, fileName string) error {
  348. zipFile, err := reader.Open(zipName)
  349. if err != nil {
  350. return err
  351. }
  352. os.Remove(fileName)
  353. file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, fs.ModePerm)
  354. if err != nil {
  355. return err
  356. }
  357. defer file.Close()
  358. _, err = io.Copy(file, zipFile)
  359. return err
  360. }
  361. err = copyZipFile("xray", xray.GetBinaryPath())
  362. if err != nil {
  363. return err
  364. }
  365. return nil
  366. }
  367. func (s *ServerService) GetLogs(count string, level string, syslog string) []string {
  368. c, _ := strconv.Atoi(count)
  369. var lines []string
  370. if syslog == "true" {
  371. cmdArgs := []string{"journalctl", "-u", "x-ui", "--no-pager", "-n", count, "-p", level}
  372. // Run the command
  373. cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
  374. var out bytes.Buffer
  375. cmd.Stdout = &out
  376. err := cmd.Run()
  377. if err != nil {
  378. return []string{"Failed to run journalctl command!"}
  379. }
  380. lines = strings.Split(out.String(), "\n")
  381. } else {
  382. lines = logger.GetLogs(c, level)
  383. }
  384. return lines
  385. }
  386. func (s *ServerService) GetConfigJson() (interface{}, error) {
  387. config, err := s.xrayService.GetXrayConfig()
  388. if err != nil {
  389. return nil, err
  390. }
  391. contents, err := json.MarshalIndent(config, "", " ")
  392. if err != nil {
  393. return nil, err
  394. }
  395. var jsonData interface{}
  396. err = json.Unmarshal(contents, &jsonData)
  397. if err != nil {
  398. return nil, err
  399. }
  400. return jsonData, nil
  401. }
  402. func (s *ServerService) GetDb() ([]byte, error) {
  403. // Update by manually trigger a checkpoint operation
  404. err := database.Checkpoint()
  405. if err != nil {
  406. return nil, err
  407. }
  408. // Open the file for reading
  409. file, err := os.Open(config.GetDBPath())
  410. if err != nil {
  411. return nil, err
  412. }
  413. defer file.Close()
  414. // Read the file contents
  415. fileContents, err := io.ReadAll(file)
  416. if err != nil {
  417. return nil, err
  418. }
  419. return fileContents, nil
  420. }
  421. func (s *ServerService) ImportDB(file multipart.File) error {
  422. // Check if the file is a SQLite database
  423. isValidDb, err := database.IsSQLiteDB(file)
  424. if err != nil {
  425. return common.NewErrorf("Error checking db file format: %v", err)
  426. }
  427. if !isValidDb {
  428. return common.NewError("Invalid db file format")
  429. }
  430. // Reset the file reader to the beginning
  431. _, err = file.Seek(0, 0)
  432. if err != nil {
  433. return common.NewErrorf("Error resetting file reader: %v", err)
  434. }
  435. // Save the file as temporary file
  436. tempPath := fmt.Sprintf("%s.temp", config.GetDBPath())
  437. // Remove the existing fallback file (if any) before creating one
  438. _, err = os.Stat(tempPath)
  439. if err == nil {
  440. errRemove := os.Remove(tempPath)
  441. if errRemove != nil {
  442. return common.NewErrorf("Error removing existing temporary db file: %v", errRemove)
  443. }
  444. }
  445. // Create the temporary file
  446. tempFile, err := os.Create(tempPath)
  447. if err != nil {
  448. return common.NewErrorf("Error creating temporary db file: %v", err)
  449. }
  450. defer tempFile.Close()
  451. // Remove temp file before returning
  452. defer os.Remove(tempPath)
  453. // Save uploaded file to temporary file
  454. _, err = io.Copy(tempFile, file)
  455. if err != nil {
  456. return common.NewErrorf("Error saving db: %v", err)
  457. }
  458. // Check if we can init db or not
  459. err = database.InitDB(tempPath)
  460. if err != nil {
  461. return common.NewErrorf("Error checking db: %v", err)
  462. }
  463. // Stop Xray
  464. s.StopXrayService()
  465. // Backup the current database for fallback
  466. fallbackPath := fmt.Sprintf("%s.backup", config.GetDBPath())
  467. // Remove the existing fallback file (if any)
  468. _, err = os.Stat(fallbackPath)
  469. if err == nil {
  470. errRemove := os.Remove(fallbackPath)
  471. if errRemove != nil {
  472. return common.NewErrorf("Error removing existing fallback db file: %v", errRemove)
  473. }
  474. }
  475. // Move the current database to the fallback location
  476. err = os.Rename(config.GetDBPath(), fallbackPath)
  477. if err != nil {
  478. return common.NewErrorf("Error backing up temporary db file: %v", err)
  479. }
  480. // Remove the temporary file before returning
  481. defer os.Remove(fallbackPath)
  482. // Move temp to DB path
  483. err = os.Rename(tempPath, config.GetDBPath())
  484. if err != nil {
  485. errRename := os.Rename(fallbackPath, config.GetDBPath())
  486. if errRename != nil {
  487. return common.NewErrorf("Error moving db file and restoring fallback: %v", errRename)
  488. }
  489. return common.NewErrorf("Error moving db file: %v", err)
  490. }
  491. // Migrate DB
  492. err = database.InitDB(config.GetDBPath())
  493. if err != nil {
  494. errRename := os.Rename(fallbackPath, config.GetDBPath())
  495. if errRename != nil {
  496. return common.NewErrorf("Error migrating db and restoring fallback: %v", errRename)
  497. }
  498. return common.NewErrorf("Error migrating db: %v", err)
  499. }
  500. s.inboundService.MigrateDB()
  501. // Start Xray
  502. err = s.RestartXrayService()
  503. if err != nil {
  504. return common.NewErrorf("Imported DB but Failed to start Xray: %v", err)
  505. }
  506. return nil
  507. }
  508. func (s *ServerService) GetNewX25519Cert() (interface{}, error) {
  509. // Run the command
  510. cmd := exec.Command(xray.GetBinaryPath(), "x25519")
  511. var out bytes.Buffer
  512. cmd.Stdout = &out
  513. err := cmd.Run()
  514. if err != nil {
  515. return nil, err
  516. }
  517. lines := strings.Split(out.String(), "\n")
  518. privateKeyLine := strings.Split(lines[0], ":")
  519. publicKeyLine := strings.Split(lines[1], ":")
  520. privateKey := strings.TrimSpace(privateKeyLine[1])
  521. publicKey := strings.TrimSpace(publicKeyLine[1])
  522. keyPair := map[string]interface{}{
  523. "privateKey": privateKey,
  524. "publicKey": publicKey,
  525. }
  526. return keyPair, nil
  527. }