1
0

server.go 14 KB

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