server.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. "strings"
  15. "time"
  16. "x-ui/config"
  17. "x-ui/database"
  18. "x-ui/logger"
  19. "x-ui/util/common"
  20. "x-ui/util/sys"
  21. "x-ui/xray"
  22. "github.com/shirou/gopsutil/v3/cpu"
  23. "github.com/shirou/gopsutil/v3/disk"
  24. "github.com/shirou/gopsutil/v3/host"
  25. "github.com/shirou/gopsutil/v3/load"
  26. "github.com/shirou/gopsutil/v3/mem"
  27. "github.com/shirou/gopsutil/v3/net"
  28. )
  29. type ProcessState string
  30. const (
  31. Running ProcessState = "running"
  32. Stop ProcessState = "stop"
  33. Error ProcessState = "error"
  34. )
  35. type Status struct {
  36. T time.Time `json:"-"`
  37. Cpu float64 `json:"cpu"`
  38. CpuCores int `json:"cpuCores"`
  39. CpuSpeedMhz float64 `json:"cpuSpeedMhz"`
  40. Mem struct {
  41. Current uint64 `json:"current"`
  42. Total uint64 `json:"total"`
  43. } `json:"mem"`
  44. Swap struct {
  45. Current uint64 `json:"current"`
  46. Total uint64 `json:"total"`
  47. } `json:"swap"`
  48. Disk struct {
  49. Current uint64 `json:"current"`
  50. Total uint64 `json:"total"`
  51. } `json:"disk"`
  52. Xray struct {
  53. State ProcessState `json:"state"`
  54. ErrorMsg string `json:"errorMsg"`
  55. Version string `json:"version"`
  56. } `json:"xray"`
  57. Uptime uint64 `json:"uptime"`
  58. Loads []float64 `json:"loads"`
  59. TcpCount int `json:"tcpCount"`
  60. UdpCount int `json:"udpCount"`
  61. NetIO struct {
  62. Up uint64 `json:"up"`
  63. Down uint64 `json:"down"`
  64. } `json:"netIO"`
  65. NetTraffic struct {
  66. Sent uint64 `json:"sent"`
  67. Recv uint64 `json:"recv"`
  68. } `json:"netTraffic"`
  69. PublicIP struct {
  70. IPv4 string `json:"ipv4"`
  71. IPv6 string `json:"ipv6"`
  72. } `json:"publicIP"`
  73. }
  74. type Release struct {
  75. TagName string `json:"tag_name"`
  76. }
  77. type ServerService struct {
  78. xrayService XrayService
  79. inboundService InboundService
  80. }
  81. func getPublicIP(url string) string {
  82. resp, err := http.Get(url)
  83. if err != nil {
  84. return "N/A"
  85. }
  86. defer resp.Body.Close()
  87. ip, err := io.ReadAll(resp.Body)
  88. if err != nil {
  89. return "N/A"
  90. }
  91. ipString := string(ip)
  92. if ipString == "" {
  93. return "N/A"
  94. }
  95. return ipString
  96. }
  97. func (s *ServerService) GetStatus(lastStatus *Status) *Status {
  98. now := time.Now()
  99. status := &Status{
  100. T: now,
  101. }
  102. percents, err := cpu.Percent(0, false)
  103. if err != nil {
  104. logger.Warning("get cpu percent failed:", err)
  105. } else {
  106. status.Cpu = percents[0]
  107. }
  108. status.CpuCores, err = cpu.Counts(false)
  109. if err != nil {
  110. logger.Warning("get cpu cores count failed:", err)
  111. }
  112. cpuInfos, err := cpu.Info()
  113. if err != nil {
  114. logger.Warning("get cpu info failed:", err)
  115. } else if len(cpuInfos) > 0 {
  116. cpuInfo := cpuInfos[0]
  117. status.CpuSpeedMhz = cpuInfo.Mhz // setting CPU speed in MHz
  118. } else {
  119. logger.Warning("could not find cpu info")
  120. }
  121. upTime, err := host.Uptime()
  122. if err != nil {
  123. logger.Warning("get uptime failed:", err)
  124. } else {
  125. status.Uptime = upTime
  126. }
  127. memInfo, err := mem.VirtualMemory()
  128. if err != nil {
  129. logger.Warning("get virtual memory failed:", err)
  130. } else {
  131. status.Mem.Current = memInfo.Used
  132. status.Mem.Total = memInfo.Total
  133. }
  134. swapInfo, err := mem.SwapMemory()
  135. if err != nil {
  136. logger.Warning("get swap memory failed:", err)
  137. } else {
  138. status.Swap.Current = swapInfo.Used
  139. status.Swap.Total = swapInfo.Total
  140. }
  141. distInfo, err := disk.Usage("/")
  142. if err != nil {
  143. logger.Warning("get dist usage failed:", err)
  144. } else {
  145. status.Disk.Current = distInfo.Used
  146. status.Disk.Total = distInfo.Total
  147. }
  148. avgState, err := load.Avg()
  149. if err != nil {
  150. logger.Warning("get load avg failed:", err)
  151. } else {
  152. status.Loads = []float64{avgState.Load1, avgState.Load5, avgState.Load15}
  153. }
  154. ioStats, err := net.IOCounters(false)
  155. if err != nil {
  156. logger.Warning("get io counters failed:", err)
  157. } else if len(ioStats) > 0 {
  158. ioStat := ioStats[0]
  159. status.NetTraffic.Sent = ioStat.BytesSent
  160. status.NetTraffic.Recv = ioStat.BytesRecv
  161. if lastStatus != nil {
  162. duration := now.Sub(lastStatus.T)
  163. seconds := float64(duration) / float64(time.Second)
  164. up := uint64(float64(status.NetTraffic.Sent-lastStatus.NetTraffic.Sent) / seconds)
  165. down := uint64(float64(status.NetTraffic.Recv-lastStatus.NetTraffic.Recv) / seconds)
  166. status.NetIO.Up = up
  167. status.NetIO.Down = down
  168. }
  169. } else {
  170. logger.Warning("can not find io counters")
  171. }
  172. status.TcpCount, err = sys.GetTCPCount()
  173. if err != nil {
  174. logger.Warning("get tcp connections failed:", err)
  175. }
  176. status.UdpCount, err = sys.GetUDPCount()
  177. if err != nil {
  178. logger.Warning("get udp connections failed:", err)
  179. }
  180. status.PublicIP.IPv4 = getPublicIP("https://api.ipify.org")
  181. status.PublicIP.IPv6 = getPublicIP("https://api6.ipify.org")
  182. if s.xrayService.IsXrayRunning() {
  183. status.Xray.State = Running
  184. status.Xray.ErrorMsg = ""
  185. } else {
  186. err := s.xrayService.GetXrayErr()
  187. if err != nil {
  188. status.Xray.State = Error
  189. } else {
  190. status.Xray.State = Stop
  191. }
  192. status.Xray.ErrorMsg = s.xrayService.GetXrayResult()
  193. }
  194. status.Xray.Version = s.xrayService.GetXrayVersion()
  195. return status
  196. }
  197. func (s *ServerService) GetXrayVersions() ([]string, error) {
  198. url := "https://api.github.com/repos/XTLS/Xray-core/releases"
  199. resp, err := http.Get(url)
  200. if err != nil {
  201. return nil, err
  202. }
  203. defer resp.Body.Close()
  204. buffer := bytes.NewBuffer(make([]byte, 8192))
  205. buffer.Reset()
  206. _, err = buffer.ReadFrom(resp.Body)
  207. if err != nil {
  208. return nil, err
  209. }
  210. releases := make([]Release, 0)
  211. err = json.Unmarshal(buffer.Bytes(), &releases)
  212. if err != nil {
  213. return nil, err
  214. }
  215. var versions []string
  216. for _, release := range releases {
  217. if release.TagName >= "v1.7.5" {
  218. versions = append(versions, release.TagName)
  219. }
  220. }
  221. return versions, nil
  222. }
  223. func (s *ServerService) StopXrayService() (string error) {
  224. err := s.xrayService.StopXray()
  225. if err != nil {
  226. logger.Error("stop xray failed:", err)
  227. return err
  228. }
  229. return nil
  230. }
  231. func (s *ServerService) RestartXrayService() (string error) {
  232. s.xrayService.StopXray()
  233. defer func() {
  234. err := s.xrayService.RestartXray(true)
  235. if err != nil {
  236. logger.Error("start xray failed:", err)
  237. }
  238. }()
  239. return nil
  240. }
  241. func (s *ServerService) downloadXRay(version string) (string, error) {
  242. osName := runtime.GOOS
  243. arch := runtime.GOARCH
  244. switch osName {
  245. case "darwin":
  246. osName = "macos"
  247. }
  248. switch arch {
  249. case "amd64":
  250. arch = "64"
  251. case "arm64":
  252. arch = "arm64-v8a"
  253. }
  254. fileName := fmt.Sprintf("Xray-%s-%s.zip", osName, arch)
  255. url := fmt.Sprintf("https://github.com/XTLS/Xray-core/releases/download/%s/%s", version, fileName)
  256. resp, err := http.Get(url)
  257. if err != nil {
  258. return "", err
  259. }
  260. defer resp.Body.Close()
  261. os.Remove(fileName)
  262. file, err := os.Create(fileName)
  263. if err != nil {
  264. return "", err
  265. }
  266. defer file.Close()
  267. _, err = io.Copy(file, resp.Body)
  268. if err != nil {
  269. return "", err
  270. }
  271. return fileName, nil
  272. }
  273. func (s *ServerService) UpdateXray(version string) error {
  274. zipFileName, err := s.downloadXRay(version)
  275. if err != nil {
  276. return err
  277. }
  278. zipFile, err := os.Open(zipFileName)
  279. if err != nil {
  280. return err
  281. }
  282. defer func() {
  283. zipFile.Close()
  284. os.Remove(zipFileName)
  285. }()
  286. stat, err := zipFile.Stat()
  287. if err != nil {
  288. return err
  289. }
  290. reader, err := zip.NewReader(zipFile, stat.Size())
  291. if err != nil {
  292. return err
  293. }
  294. s.xrayService.StopXray()
  295. defer func() {
  296. err := s.xrayService.RestartXray(true)
  297. if err != nil {
  298. logger.Error("start xray failed:", err)
  299. }
  300. }()
  301. copyZipFile := func(zipName string, fileName string) error {
  302. zipFile, err := reader.Open(zipName)
  303. if err != nil {
  304. return err
  305. }
  306. os.Remove(fileName)
  307. file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, fs.ModePerm)
  308. if err != nil {
  309. return err
  310. }
  311. defer file.Close()
  312. _, err = io.Copy(file, zipFile)
  313. return err
  314. }
  315. err = copyZipFile("xray", xray.GetBinaryPath())
  316. if err != nil {
  317. return err
  318. }
  319. err = copyZipFile("geosite.dat", xray.GetGeositePath())
  320. if err != nil {
  321. return err
  322. }
  323. err = copyZipFile("geoip.dat", xray.GetGeoipPath())
  324. if err != nil {
  325. return err
  326. }
  327. return nil
  328. }
  329. func (s *ServerService) GetLogs(count string, logLevel string) ([]string, error) {
  330. var cmdArgs []string
  331. if runtime.GOOS == "linux" {
  332. cmdArgs = []string{"journalctl", "-u", "x-ui", "--no-pager", "-n", count}
  333. if logLevel != "" {
  334. cmdArgs = append(cmdArgs, "-p", logLevel)
  335. }
  336. } else {
  337. return []string{"Unsupported operating system"}, nil
  338. }
  339. cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
  340. var out bytes.Buffer
  341. cmd.Stdout = &out
  342. err := cmd.Run()
  343. if err != nil {
  344. return nil, err
  345. }
  346. lines := strings.Split(out.String(), "\n")
  347. return lines, nil
  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. }