server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. const DebugMode = false // Set to true during development
  82. func getPublicIP(url string) string {
  83. resp, err := http.Get(url)
  84. if err != nil {
  85. if DebugMode {
  86. logger.Warning("get public IP failed:", err)
  87. }
  88. return "N/A"
  89. }
  90. defer resp.Body.Close()
  91. ip, err := io.ReadAll(resp.Body)
  92. if err != nil {
  93. if DebugMode {
  94. logger.Warning("read public IP failed:", err)
  95. }
  96. return "N/A"
  97. }
  98. if string(ip) == "" {
  99. return "N/A" // default value
  100. }
  101. return string(ip)
  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. return status
  202. }
  203. func (s *ServerService) GetXrayVersions() ([]string, error) {
  204. url := "https://api.github.com/repos/MHSanaei/Xray-core/releases"
  205. resp, err := http.Get(url)
  206. if err != nil {
  207. return nil, err
  208. }
  209. defer resp.Body.Close()
  210. buffer := bytes.NewBuffer(make([]byte, 8192))
  211. buffer.Reset()
  212. _, err = buffer.ReadFrom(resp.Body)
  213. if err != nil {
  214. return nil, err
  215. }
  216. releases := make([]Release, 0)
  217. err = json.Unmarshal(buffer.Bytes(), &releases)
  218. if err != nil {
  219. return nil, err
  220. }
  221. versions := make([]string, 0, len(releases))
  222. for _, release := range releases {
  223. versions = append(versions, release.TagName)
  224. }
  225. return versions, nil
  226. }
  227. func (s *ServerService) StopXrayService() (string error) {
  228. err := s.xrayService.StopXray()
  229. if err != nil {
  230. logger.Error("stop xray failed:", err)
  231. return err
  232. }
  233. return nil
  234. }
  235. func (s *ServerService) RestartXrayService() (string error) {
  236. s.xrayService.StopXray()
  237. defer func() {
  238. err := s.xrayService.RestartXray(true)
  239. if err != nil {
  240. logger.Error("start xray failed:", err)
  241. }
  242. }()
  243. return nil
  244. }
  245. func (s *ServerService) downloadXRay(version string) (string, error) {
  246. osName := runtime.GOOS
  247. arch := runtime.GOARCH
  248. switch osName {
  249. case "darwin":
  250. osName = "macos"
  251. }
  252. switch arch {
  253. case "amd64":
  254. arch = "64"
  255. case "arm64":
  256. arch = "arm64-v8a"
  257. }
  258. fileName := fmt.Sprintf("Xray-%s-%s.zip", osName, arch)
  259. url := fmt.Sprintf("https://github.com/MHSanaei/Xray-core/releases/download/%s/%s", version, fileName)
  260. resp, err := http.Get(url)
  261. if err != nil {
  262. return "", err
  263. }
  264. defer resp.Body.Close()
  265. os.Remove(fileName)
  266. file, err := os.Create(fileName)
  267. if err != nil {
  268. return "", err
  269. }
  270. defer file.Close()
  271. _, err = io.Copy(file, resp.Body)
  272. if err != nil {
  273. return "", err
  274. }
  275. return fileName, nil
  276. }
  277. func (s *ServerService) UpdateXray(version string) error {
  278. zipFileName, err := s.downloadXRay(version)
  279. if err != nil {
  280. return err
  281. }
  282. zipFile, err := os.Open(zipFileName)
  283. if err != nil {
  284. return err
  285. }
  286. defer func() {
  287. zipFile.Close()
  288. os.Remove(zipFileName)
  289. }()
  290. stat, err := zipFile.Stat()
  291. if err != nil {
  292. return err
  293. }
  294. reader, err := zip.NewReader(zipFile, stat.Size())
  295. if err != nil {
  296. return err
  297. }
  298. s.xrayService.StopXray()
  299. defer func() {
  300. err := s.xrayService.RestartXray(true)
  301. if err != nil {
  302. logger.Error("start xray failed:", err)
  303. }
  304. }()
  305. copyZipFile := func(zipName string, fileName string) error {
  306. zipFile, err := reader.Open(zipName)
  307. if err != nil {
  308. return err
  309. }
  310. os.Remove(fileName)
  311. file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, fs.ModePerm)
  312. if err != nil {
  313. return err
  314. }
  315. defer file.Close()
  316. _, err = io.Copy(file, zipFile)
  317. return err
  318. }
  319. err = copyZipFile("xray", xray.GetBinaryPath())
  320. if err != nil {
  321. return err
  322. }
  323. err = copyZipFile("geosite.dat", xray.GetGeositePath())
  324. if err != nil {
  325. return err
  326. }
  327. err = copyZipFile("geoip.dat", xray.GetGeoipPath())
  328. if err != nil {
  329. return err
  330. }
  331. err = copyZipFile("iran.dat", xray.GetIranPath())
  332. if err != nil {
  333. return err
  334. }
  335. return nil
  336. }
  337. func (s *ServerService) GetLogs(count string) ([]string, error) {
  338. // Define the journalctl command and its arguments
  339. var cmdArgs []string
  340. if runtime.GOOS == "linux" {
  341. cmdArgs = []string{"journalctl", "-u", "x-ui", "--no-pager", "-n", count}
  342. } else {
  343. return []string{"Unsupported operating system"}, nil
  344. }
  345. // Run the command
  346. cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
  347. var out bytes.Buffer
  348. cmd.Stdout = &out
  349. err := cmd.Run()
  350. if err != nil {
  351. return nil, err
  352. }
  353. lines := strings.Split(out.String(), "\n")
  354. return lines, nil
  355. }
  356. func (s *ServerService) GetConfigJson() (interface{}, error) {
  357. // Open the file for reading
  358. file, err := os.Open(xray.GetConfigPath())
  359. if err != nil {
  360. return nil, err
  361. }
  362. defer file.Close()
  363. // Read the file contents
  364. fileContents, err := io.ReadAll(file)
  365. if err != nil {
  366. return nil, err
  367. }
  368. var jsonData interface{}
  369. err = json.Unmarshal(fileContents, &jsonData)
  370. if err != nil {
  371. return nil, err
  372. }
  373. return jsonData, nil
  374. }
  375. func (s *ServerService) GetDb() ([]byte, error) {
  376. // Open the file for reading
  377. file, err := os.Open(config.GetDBPath())
  378. if err != nil {
  379. return nil, err
  380. }
  381. defer file.Close()
  382. // Read the file contents
  383. fileContents, err := io.ReadAll(file)
  384. if err != nil {
  385. return nil, err
  386. }
  387. return fileContents, nil
  388. }
  389. func (s *ServerService) ImportDB(file multipart.File) error {
  390. // Check if the file is a SQLite database
  391. isValidDb, err := database.IsSQLiteDB(file)
  392. if err != nil {
  393. return common.NewErrorf("Error checking db file format: %v", err)
  394. }
  395. if !isValidDb {
  396. return common.NewError("Invalid db file format")
  397. }
  398. // Reset the file reader to the beginning
  399. _, err = file.Seek(0, 0)
  400. if err != nil {
  401. return common.NewErrorf("Error resetting file reader: %v", err)
  402. }
  403. // Save the file as temporary file
  404. tempPath := fmt.Sprintf("%s.temp", config.GetDBPath())
  405. // Remove the existing fallback file (if any) before creating one
  406. _, err = os.Stat(tempPath)
  407. if err == nil {
  408. errRemove := os.Remove(tempPath)
  409. if errRemove != nil {
  410. return common.NewErrorf("Error removing existing temporary db file: %v", errRemove)
  411. }
  412. }
  413. // Create the temporary file
  414. tempFile, err := os.Create(tempPath)
  415. if err != nil {
  416. return common.NewErrorf("Error creating temporary db file: %v", err)
  417. }
  418. defer tempFile.Close()
  419. // Remove temp file before returning
  420. defer os.Remove(tempPath)
  421. // Save uploaded file to temporary file
  422. _, err = io.Copy(tempFile, file)
  423. if err != nil {
  424. return common.NewErrorf("Error saving db: %v", err)
  425. }
  426. // Check if we can init db or not
  427. err = database.InitDB(tempPath)
  428. if err != nil {
  429. return common.NewErrorf("Error checking db: %v", err)
  430. }
  431. // Stop Xray
  432. s.StopXrayService()
  433. // Backup the current database for fallback
  434. fallbackPath := fmt.Sprintf("%s.backup", config.GetDBPath())
  435. // Remove the existing fallback file (if any)
  436. _, err = os.Stat(fallbackPath)
  437. if err == nil {
  438. errRemove := os.Remove(fallbackPath)
  439. if errRemove != nil {
  440. return common.NewErrorf("Error removing existing fallback db file: %v", errRemove)
  441. }
  442. }
  443. // Move the current database to the fallback location
  444. err = os.Rename(config.GetDBPath(), fallbackPath)
  445. if err != nil {
  446. return common.NewErrorf("Error backing up temporary db file: %v", err)
  447. }
  448. // Remove the temporary file before returning
  449. defer os.Remove(fallbackPath)
  450. // Move temp to DB path
  451. err = os.Rename(tempPath, config.GetDBPath())
  452. if err != nil {
  453. errRename := os.Rename(fallbackPath, config.GetDBPath())
  454. if errRename != nil {
  455. return common.NewErrorf("Error moving db file and restoring fallback: %v", errRename)
  456. }
  457. return common.NewErrorf("Error moving db file: %v", err)
  458. }
  459. // Migrate DB
  460. err = database.InitDB(config.GetDBPath())
  461. if err != nil {
  462. errRename := os.Rename(fallbackPath, config.GetDBPath())
  463. if errRename != nil {
  464. return common.NewErrorf("Error migrating db and restoring fallback: %v", errRename)
  465. }
  466. return common.NewErrorf("Error migrating db: %v", err)
  467. }
  468. s.inboundService.MigrateDB()
  469. // Start Xray
  470. err = s.RestartXrayService()
  471. if err != nil {
  472. return common.NewErrorf("Imported DB but Failed to start Xray: %v", err)
  473. }
  474. return nil
  475. }
  476. func (s *ServerService) GetNewX25519Cert() (interface{}, error) {
  477. // Run the command
  478. cmd := exec.Command(xray.GetBinaryPath(), "x25519")
  479. var out bytes.Buffer
  480. cmd.Stdout = &out
  481. err := cmd.Run()
  482. if err != nil {
  483. return nil, err
  484. }
  485. lines := strings.Split(out.String(), "\n")
  486. privateKeyLine := strings.Split(lines[0], ":")
  487. publicKeyLine := strings.Split(lines[1], ":")
  488. privateKey := strings.TrimSpace(privateKeyLine[1])
  489. publicKey := strings.TrimSpace(publicKeyLine[1])
  490. keyPair := map[string]interface{}{
  491. "privateKey": privateKey,
  492. "publicKey": publicKey,
  493. }
  494. return keyPair, nil
  495. }