1
0

server.go 13 KB

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