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