server.go 12 KB

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