server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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.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. err = copyZipFile("geosite.dat", xray.GetGeositePath())
  335. if err != nil {
  336. return err
  337. }
  338. err = copyZipFile("geoip.dat", xray.GetGeoipPath())
  339. if err != nil {
  340. return err
  341. }
  342. return nil
  343. }
  344. func (s *ServerService) GetLogs(count string, level string, syslog string) []string {
  345. c, _ := strconv.Atoi(count)
  346. var lines []string
  347. if syslog == "true" {
  348. cmdArgs := []string{"journalctl", "-u", "x-ui", "--no-pager", "-n", count, "-p", level}
  349. // Run the command
  350. cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
  351. var out bytes.Buffer
  352. cmd.Stdout = &out
  353. err := cmd.Run()
  354. if err != nil {
  355. return []string{"Failed to run journalctl command!"}
  356. }
  357. lines = strings.Split(out.String(), "\n")
  358. } else {
  359. lines = logger.GetLogs(c, level)
  360. }
  361. return lines
  362. }
  363. func (s *ServerService) GetConfigJson() (interface{}, error) {
  364. config, err := s.xrayService.GetXrayConfig()
  365. if err != nil {
  366. return nil, err
  367. }
  368. contents, err := json.MarshalIndent(config, "", " ")
  369. if err != nil {
  370. return nil, err
  371. }
  372. var jsonData interface{}
  373. err = json.Unmarshal(contents, &jsonData)
  374. if err != nil {
  375. return nil, err
  376. }
  377. return jsonData, nil
  378. }
  379. func (s *ServerService) GetDb() ([]byte, error) {
  380. // Open the file for reading
  381. file, err := os.Open(config.GetDBPath())
  382. if err != nil {
  383. return nil, err
  384. }
  385. defer file.Close()
  386. // Read the file contents
  387. fileContents, err := io.ReadAll(file)
  388. if err != nil {
  389. return nil, err
  390. }
  391. return fileContents, nil
  392. }
  393. func (s *ServerService) ImportDB(file multipart.File) error {
  394. // Check if the file is a SQLite database
  395. isValidDb, err := database.IsSQLiteDB(file)
  396. if err != nil {
  397. return common.NewErrorf("Error checking db file format: %v", err)
  398. }
  399. if !isValidDb {
  400. return common.NewError("Invalid db file format")
  401. }
  402. // Reset the file reader to the beginning
  403. _, err = file.Seek(0, 0)
  404. if err != nil {
  405. return common.NewErrorf("Error resetting file reader: %v", err)
  406. }
  407. // Save the file as temporary file
  408. tempPath := fmt.Sprintf("%s.temp", config.GetDBPath())
  409. // Remove the existing fallback file (if any) before creating one
  410. _, err = os.Stat(tempPath)
  411. if err == nil {
  412. errRemove := os.Remove(tempPath)
  413. if errRemove != nil {
  414. return common.NewErrorf("Error removing existing temporary db file: %v", errRemove)
  415. }
  416. }
  417. // Create the temporary file
  418. tempFile, err := os.Create(tempPath)
  419. if err != nil {
  420. return common.NewErrorf("Error creating temporary db file: %v", err)
  421. }
  422. defer tempFile.Close()
  423. // Remove temp file before returning
  424. defer os.Remove(tempPath)
  425. // Save uploaded file to temporary file
  426. _, err = io.Copy(tempFile, file)
  427. if err != nil {
  428. return common.NewErrorf("Error saving db: %v", err)
  429. }
  430. // Check if we can init db or not
  431. err = database.InitDB(tempPath)
  432. if err != nil {
  433. return common.NewErrorf("Error checking db: %v", err)
  434. }
  435. // Stop Xray
  436. s.StopXrayService()
  437. // Backup the current database for fallback
  438. fallbackPath := fmt.Sprintf("%s.backup", config.GetDBPath())
  439. // Remove the existing fallback file (if any)
  440. _, err = os.Stat(fallbackPath)
  441. if err == nil {
  442. errRemove := os.Remove(fallbackPath)
  443. if errRemove != nil {
  444. return common.NewErrorf("Error removing existing fallback db file: %v", errRemove)
  445. }
  446. }
  447. // Move the current database to the fallback location
  448. err = os.Rename(config.GetDBPath(), fallbackPath)
  449. if err != nil {
  450. return common.NewErrorf("Error backing up temporary db file: %v", err)
  451. }
  452. // Remove the temporary file before returning
  453. defer os.Remove(fallbackPath)
  454. // Move temp to DB path
  455. err = os.Rename(tempPath, config.GetDBPath())
  456. if err != nil {
  457. errRename := os.Rename(fallbackPath, config.GetDBPath())
  458. if errRename != nil {
  459. return common.NewErrorf("Error moving db file and restoring fallback: %v", errRename)
  460. }
  461. return common.NewErrorf("Error moving db file: %v", err)
  462. }
  463. // Migrate DB
  464. err = database.InitDB(config.GetDBPath())
  465. if err != nil {
  466. errRename := os.Rename(fallbackPath, config.GetDBPath())
  467. if errRename != nil {
  468. return common.NewErrorf("Error migrating db and restoring fallback: %v", errRename)
  469. }
  470. return common.NewErrorf("Error migrating db: %v", err)
  471. }
  472. s.inboundService.MigrateDB()
  473. // Start Xray
  474. err = s.RestartXrayService()
  475. if err != nil {
  476. return common.NewErrorf("Imported DB but Failed to start Xray: %v", err)
  477. }
  478. return nil
  479. }
  480. func (s *ServerService) GetNewX25519Cert() (interface{}, error) {
  481. // Run the command
  482. cmd := exec.Command(xray.GetBinaryPath(), "x25519")
  483. var out bytes.Buffer
  484. cmd.Stdout = &out
  485. err := cmd.Run()
  486. if err != nil {
  487. return nil, err
  488. }
  489. lines := strings.Split(out.String(), "\n")
  490. privateKeyLine := strings.Split(lines[0], ":")
  491. publicKeyLine := strings.Split(lines[1], ":")
  492. privateKey := strings.TrimSpace(privateKeyLine[1])
  493. publicKey := strings.TrimSpace(publicKeyLine[1])
  494. keyPair := map[string]interface{}{
  495. "privateKey": privateKey,
  496. "publicKey": publicKey,
  497. }
  498. return keyPair, nil
  499. }