server.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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. downloadFile := func(fileName string, url string) error {
  331. os.Remove(fileName)
  332. file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, fs.ModePerm)
  333. if err != nil {
  334. return err
  335. }
  336. defer file.Close()
  337. resp, err := http.Get(url)
  338. if err != nil {
  339. return err
  340. }
  341. defer resp.Body.Close()
  342. if resp.StatusCode != http.StatusOK {
  343. return fmt.Errorf("download file failed: %s", resp.Status)
  344. }
  345. _, err = io.Copy(file, resp.Body)
  346. return err
  347. }
  348. copyFiles := map[string]string{
  349. "xray": xray.GetBinaryPath(),
  350. "geosite.dat": xray.GetGeositePath(),
  351. "geoip.dat": xray.GetGeoipPath(),
  352. }
  353. downloadFiles := map[string]string{
  354. xray.GetIranPath(): "https://github.com/MasterKia/iran-hosted-domains/releases/latest/download/iran.dat",
  355. }
  356. for fileName, filePath := range copyFiles {
  357. err := copyZipFile(fileName, filePath)
  358. if err != nil {
  359. return err
  360. }
  361. }
  362. for fileName, filePath := range downloadFiles {
  363. err := downloadFile(fileName, filePath)
  364. if err != nil {
  365. return err
  366. }
  367. }
  368. return nil
  369. }
  370. func (s *ServerService) GetLogs(count string, level string, syslog string) []string {
  371. c, _ := strconv.Atoi(count)
  372. var lines []string
  373. if syslog == "true" {
  374. cmdArgs := []string{"journalctl", "-u", "x-ui", "--no-pager", "-n", count, "-p", level}
  375. // Run the command
  376. cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
  377. var out bytes.Buffer
  378. cmd.Stdout = &out
  379. err := cmd.Run()
  380. if err != nil {
  381. return []string{"Failed to run journalctl command!"}
  382. }
  383. lines = strings.Split(out.String(), "\n")
  384. } else {
  385. lines = logger.GetLogs(c, level)
  386. }
  387. return lines
  388. }
  389. func (s *ServerService) GetConfigJson() (interface{}, error) {
  390. config, err := s.xrayService.GetXrayConfig()
  391. if err != nil {
  392. return nil, err
  393. }
  394. contents, err := json.MarshalIndent(config, "", " ")
  395. if err != nil {
  396. return nil, err
  397. }
  398. var jsonData interface{}
  399. err = json.Unmarshal(contents, &jsonData)
  400. if err != nil {
  401. return nil, err
  402. }
  403. return jsonData, nil
  404. }
  405. func (s *ServerService) GetDb() ([]byte, error) {
  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. }