server.go 13 KB

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