1
0

server.go 23 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. package service
  2. import (
  3. "archive/zip"
  4. "bufio"
  5. "bytes"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "io/fs"
  10. "mime/multipart"
  11. "net/http"
  12. "os"
  13. "os/exec"
  14. "path/filepath"
  15. "runtime"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "x-ui/config"
  20. "x-ui/database"
  21. "x-ui/logger"
  22. "x-ui/util/common"
  23. "x-ui/util/sys"
  24. "x-ui/xray"
  25. "github.com/google/uuid"
  26. "github.com/shirou/gopsutil/v4/cpu"
  27. "github.com/shirou/gopsutil/v4/disk"
  28. "github.com/shirou/gopsutil/v4/host"
  29. "github.com/shirou/gopsutil/v4/load"
  30. "github.com/shirou/gopsutil/v4/mem"
  31. "github.com/shirou/gopsutil/v4/net"
  32. )
  33. type ProcessState string
  34. const (
  35. Running ProcessState = "running"
  36. Stop ProcessState = "stop"
  37. Error ProcessState = "error"
  38. )
  39. type Status struct {
  40. T time.Time `json:"-"`
  41. Cpu float64 `json:"cpu"`
  42. CpuCores int `json:"cpuCores"`
  43. LogicalPro int `json:"logicalPro"`
  44. CpuSpeedMhz float64 `json:"cpuSpeedMhz"`
  45. Mem struct {
  46. Current uint64 `json:"current"`
  47. Total uint64 `json:"total"`
  48. } `json:"mem"`
  49. Swap struct {
  50. Current uint64 `json:"current"`
  51. Total uint64 `json:"total"`
  52. } `json:"swap"`
  53. Disk struct {
  54. Current uint64 `json:"current"`
  55. Total uint64 `json:"total"`
  56. } `json:"disk"`
  57. Xray struct {
  58. State ProcessState `json:"state"`
  59. ErrorMsg string `json:"errorMsg"`
  60. Version string `json:"version"`
  61. } `json:"xray"`
  62. Uptime uint64 `json:"uptime"`
  63. Loads []float64 `json:"loads"`
  64. TcpCount int `json:"tcpCount"`
  65. UdpCount int `json:"udpCount"`
  66. NetIO struct {
  67. Up uint64 `json:"up"`
  68. Down uint64 `json:"down"`
  69. } `json:"netIO"`
  70. NetTraffic struct {
  71. Sent uint64 `json:"sent"`
  72. Recv uint64 `json:"recv"`
  73. } `json:"netTraffic"`
  74. PublicIP struct {
  75. IPv4 string `json:"ipv4"`
  76. IPv6 string `json:"ipv6"`
  77. } `json:"publicIP"`
  78. AppStats struct {
  79. Threads uint32 `json:"threads"`
  80. Mem uint64 `json:"mem"`
  81. Uptime uint64 `json:"uptime"`
  82. } `json:"appStats"`
  83. }
  84. type Release struct {
  85. TagName string `json:"tag_name"`
  86. }
  87. type ServerService struct {
  88. xrayService XrayService
  89. inboundService InboundService
  90. cachedIPv4 string
  91. cachedIPv6 string
  92. noIPv6 bool
  93. }
  94. type LogEntry struct {
  95. DateTime time.Time
  96. FromAddress string
  97. ToAddress string
  98. Inbound string
  99. Outbound string
  100. Email string
  101. Event int
  102. }
  103. func getPublicIP(url string) string {
  104. client := &http.Client{
  105. Timeout: 3 * time.Second,
  106. }
  107. resp, err := client.Get(url)
  108. if err != nil {
  109. return "N/A"
  110. }
  111. defer resp.Body.Close()
  112. // Don't retry if access is blocked or region-restricted
  113. if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusUnavailableForLegalReasons {
  114. return "N/A"
  115. }
  116. if resp.StatusCode != http.StatusOK {
  117. return "N/A"
  118. }
  119. ip, err := io.ReadAll(resp.Body)
  120. if err != nil {
  121. return "N/A"
  122. }
  123. ipString := strings.TrimSpace(string(ip))
  124. if ipString == "" {
  125. return "N/A"
  126. }
  127. return ipString
  128. }
  129. func (s *ServerService) GetStatus(lastStatus *Status) *Status {
  130. now := time.Now()
  131. status := &Status{
  132. T: now,
  133. }
  134. // CPU stats
  135. percents, err := cpu.Percent(0, false)
  136. if err != nil {
  137. logger.Warning("get cpu percent failed:", err)
  138. } else {
  139. status.Cpu = percents[0]
  140. }
  141. status.CpuCores, err = cpu.Counts(false)
  142. if err != nil {
  143. logger.Warning("get cpu cores count failed:", err)
  144. }
  145. status.LogicalPro = runtime.NumCPU()
  146. cpuInfos, err := cpu.Info()
  147. if err != nil {
  148. logger.Warning("get cpu info failed:", err)
  149. } else if len(cpuInfos) > 0 {
  150. status.CpuSpeedMhz = cpuInfos[0].Mhz
  151. } else {
  152. logger.Warning("could not find cpu info")
  153. }
  154. // Uptime
  155. upTime, err := host.Uptime()
  156. if err != nil {
  157. logger.Warning("get uptime failed:", err)
  158. } else {
  159. status.Uptime = upTime
  160. }
  161. // Memory stats
  162. memInfo, err := mem.VirtualMemory()
  163. if err != nil {
  164. logger.Warning("get virtual memory failed:", err)
  165. } else {
  166. status.Mem.Current = memInfo.Used
  167. status.Mem.Total = memInfo.Total
  168. }
  169. swapInfo, err := mem.SwapMemory()
  170. if err != nil {
  171. logger.Warning("get swap memory failed:", err)
  172. } else {
  173. status.Swap.Current = swapInfo.Used
  174. status.Swap.Total = swapInfo.Total
  175. }
  176. // Disk stats
  177. diskInfo, err := disk.Usage("/")
  178. if err != nil {
  179. logger.Warning("get disk usage failed:", err)
  180. } else {
  181. status.Disk.Current = diskInfo.Used
  182. status.Disk.Total = diskInfo.Total
  183. }
  184. // Load averages
  185. avgState, err := load.Avg()
  186. if err != nil {
  187. logger.Warning("get load avg failed:", err)
  188. } else {
  189. status.Loads = []float64{avgState.Load1, avgState.Load5, avgState.Load15}
  190. }
  191. // Network stats
  192. ioStats, err := net.IOCounters(false)
  193. if err != nil {
  194. logger.Warning("get io counters failed:", err)
  195. } else if len(ioStats) > 0 {
  196. ioStat := ioStats[0]
  197. status.NetTraffic.Sent = ioStat.BytesSent
  198. status.NetTraffic.Recv = ioStat.BytesRecv
  199. if lastStatus != nil {
  200. duration := now.Sub(lastStatus.T)
  201. seconds := float64(duration) / float64(time.Second)
  202. up := uint64(float64(status.NetTraffic.Sent-lastStatus.NetTraffic.Sent) / seconds)
  203. down := uint64(float64(status.NetTraffic.Recv-lastStatus.NetTraffic.Recv) / seconds)
  204. status.NetIO.Up = up
  205. status.NetIO.Down = down
  206. }
  207. } else {
  208. logger.Warning("can not find io counters")
  209. }
  210. // TCP/UDP connections
  211. status.TcpCount, err = sys.GetTCPCount()
  212. if err != nil {
  213. logger.Warning("get tcp connections failed:", err)
  214. }
  215. status.UdpCount, err = sys.GetUDPCount()
  216. if err != nil {
  217. logger.Warning("get udp connections failed:", err)
  218. }
  219. // IP fetching with caching
  220. showIp4ServiceLists := []string{
  221. "https://api4.ipify.org",
  222. "https://ipv4.icanhazip.com",
  223. "https://v4.api.ipinfo.io/ip",
  224. "https://ipv4.myexternalip.com/raw",
  225. "https://4.ident.me",
  226. "https://check-host.net/ip",
  227. }
  228. showIp6ServiceLists := []string{
  229. "https://api6.ipify.org",
  230. "https://ipv6.icanhazip.com",
  231. "https://v6.api.ipinfo.io/ip",
  232. "https://ipv6.myexternalip.com/raw",
  233. "https://6.ident.me",
  234. }
  235. if s.cachedIPv4 == "" {
  236. for _, ip4Service := range showIp4ServiceLists {
  237. s.cachedIPv4 = getPublicIP(ip4Service)
  238. if s.cachedIPv4 != "N/A" {
  239. break
  240. }
  241. }
  242. }
  243. if s.cachedIPv6 == "" && !s.noIPv6 {
  244. for _, ip6Service := range showIp6ServiceLists {
  245. s.cachedIPv6 = getPublicIP(ip6Service)
  246. if s.cachedIPv6 != "N/A" {
  247. break
  248. }
  249. }
  250. }
  251. if s.cachedIPv6 == "N/A" {
  252. s.noIPv6 = true
  253. }
  254. status.PublicIP.IPv4 = s.cachedIPv4
  255. status.PublicIP.IPv6 = s.cachedIPv6
  256. // Xray status
  257. if s.xrayService.IsXrayRunning() {
  258. status.Xray.State = Running
  259. status.Xray.ErrorMsg = ""
  260. } else {
  261. err := s.xrayService.GetXrayErr()
  262. if err != nil {
  263. status.Xray.State = Error
  264. } else {
  265. status.Xray.State = Stop
  266. }
  267. status.Xray.ErrorMsg = s.xrayService.GetXrayResult()
  268. }
  269. status.Xray.Version = s.xrayService.GetXrayVersion()
  270. // Application stats
  271. var rtm runtime.MemStats
  272. runtime.ReadMemStats(&rtm)
  273. status.AppStats.Mem = rtm.Sys
  274. status.AppStats.Threads = uint32(runtime.NumGoroutine())
  275. if p != nil && p.IsRunning() {
  276. status.AppStats.Uptime = p.GetUptime()
  277. } else {
  278. status.AppStats.Uptime = 0
  279. }
  280. return status
  281. }
  282. func (s *ServerService) GetXrayVersions() ([]string, error) {
  283. const (
  284. XrayURL = "https://api.github.com/repos/XTLS/Xray-core/releases"
  285. bufferSize = 8192
  286. )
  287. resp, err := http.Get(XrayURL)
  288. if err != nil {
  289. return nil, err
  290. }
  291. defer resp.Body.Close()
  292. buffer := bytes.NewBuffer(make([]byte, bufferSize))
  293. buffer.Reset()
  294. if _, err := buffer.ReadFrom(resp.Body); err != nil {
  295. return nil, err
  296. }
  297. var releases []Release
  298. if err := json.Unmarshal(buffer.Bytes(), &releases); err != nil {
  299. return nil, err
  300. }
  301. var versions []string
  302. for _, release := range releases {
  303. tagVersion := strings.TrimPrefix(release.TagName, "v")
  304. tagParts := strings.Split(tagVersion, ".")
  305. if len(tagParts) != 3 {
  306. continue
  307. }
  308. major, err1 := strconv.Atoi(tagParts[0])
  309. minor, err2 := strconv.Atoi(tagParts[1])
  310. patch, err3 := strconv.Atoi(tagParts[2])
  311. if err1 != nil || err2 != nil || err3 != nil {
  312. continue
  313. }
  314. if major > 25 || (major == 25 && minor > 9) || (major == 25 && minor == 9 && patch >= 11) {
  315. versions = append(versions, release.TagName)
  316. }
  317. }
  318. return versions, nil
  319. }
  320. func (s *ServerService) StopXrayService() error {
  321. err := s.xrayService.StopXray()
  322. if err != nil {
  323. logger.Error("stop xray failed:", err)
  324. return err
  325. }
  326. return nil
  327. }
  328. func (s *ServerService) RestartXrayService() error {
  329. err := s.xrayService.RestartXray(true)
  330. if err != nil {
  331. logger.Error("start xray failed:", err)
  332. return err
  333. }
  334. return nil
  335. }
  336. func (s *ServerService) downloadXRay(version string) (string, error) {
  337. osName := runtime.GOOS
  338. arch := runtime.GOARCH
  339. switch osName {
  340. case "darwin":
  341. osName = "macos"
  342. case "windows":
  343. osName = "windows"
  344. }
  345. switch arch {
  346. case "amd64":
  347. arch = "64"
  348. case "arm64":
  349. arch = "arm64-v8a"
  350. case "armv7":
  351. arch = "arm32-v7a"
  352. case "armv6":
  353. arch = "arm32-v6"
  354. case "armv5":
  355. arch = "arm32-v5"
  356. case "386":
  357. arch = "32"
  358. case "s390x":
  359. arch = "s390x"
  360. }
  361. fileName := fmt.Sprintf("Xray-%s-%s.zip", osName, arch)
  362. url := fmt.Sprintf("https://github.com/XTLS/Xray-core/releases/download/%s/%s", version, fileName)
  363. resp, err := http.Get(url)
  364. if err != nil {
  365. return "", err
  366. }
  367. defer resp.Body.Close()
  368. os.Remove(fileName)
  369. file, err := os.Create(fileName)
  370. if err != nil {
  371. return "", err
  372. }
  373. defer file.Close()
  374. _, err = io.Copy(file, resp.Body)
  375. if err != nil {
  376. return "", err
  377. }
  378. return fileName, nil
  379. }
  380. func (s *ServerService) UpdateXray(version string) error {
  381. // 1. Stop xray before doing anything
  382. if err := s.StopXrayService(); err != nil {
  383. logger.Warning("failed to stop xray before update:", err)
  384. }
  385. // 2. Download the zip
  386. zipFileName, err := s.downloadXRay(version)
  387. if err != nil {
  388. return err
  389. }
  390. defer os.Remove(zipFileName)
  391. zipFile, err := os.Open(zipFileName)
  392. if err != nil {
  393. return err
  394. }
  395. defer zipFile.Close()
  396. stat, err := zipFile.Stat()
  397. if err != nil {
  398. return err
  399. }
  400. reader, err := zip.NewReader(zipFile, stat.Size())
  401. if err != nil {
  402. return err
  403. }
  404. // 3. Helper to extract files
  405. copyZipFile := func(zipName string, fileName string) error {
  406. zipFile, err := reader.Open(zipName)
  407. if err != nil {
  408. return err
  409. }
  410. defer zipFile.Close()
  411. os.MkdirAll(filepath.Dir(fileName), 0755)
  412. os.Remove(fileName)
  413. file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, fs.ModePerm)
  414. if err != nil {
  415. return err
  416. }
  417. defer file.Close()
  418. _, err = io.Copy(file, zipFile)
  419. return err
  420. }
  421. // 4. Extract correct binary
  422. if runtime.GOOS == "windows" {
  423. targetBinary := filepath.Join("bin", "xray-windows-amd64.exe")
  424. err = copyZipFile("xray.exe", targetBinary)
  425. } else {
  426. err = copyZipFile("xray", xray.GetBinaryPath())
  427. }
  428. if err != nil {
  429. return err
  430. }
  431. // 5. Restart xray
  432. if err := s.xrayService.RestartXray(true); err != nil {
  433. logger.Error("start xray failed:", err)
  434. return err
  435. }
  436. return nil
  437. }
  438. func (s *ServerService) GetLogs(count string, level string, syslog string) []string {
  439. c, _ := strconv.Atoi(count)
  440. var lines []string
  441. if syslog == "true" {
  442. cmdArgs := []string{"journalctl", "-u", "x-ui", "--no-pager", "-n", count, "-p", level}
  443. // Run the command
  444. cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
  445. var out bytes.Buffer
  446. cmd.Stdout = &out
  447. err := cmd.Run()
  448. if err != nil {
  449. return []string{"Failed to run journalctl command!"}
  450. }
  451. lines = strings.Split(out.String(), "\n")
  452. } else {
  453. lines = logger.GetLogs(c, level)
  454. }
  455. return lines
  456. }
  457. func (s *ServerService) GetXrayLogs(
  458. count string,
  459. filter string,
  460. showDirect string,
  461. showBlocked string,
  462. showProxy string,
  463. freedoms []string,
  464. blackholes []string) []LogEntry {
  465. const (
  466. Direct = iota
  467. Blocked
  468. Proxied
  469. )
  470. countInt, _ := strconv.Atoi(count)
  471. var entries []LogEntry
  472. pathToAccessLog, err := xray.GetAccessLogPath()
  473. if err != nil {
  474. return nil
  475. }
  476. file, err := os.Open(pathToAccessLog)
  477. if err != nil {
  478. return nil
  479. }
  480. defer file.Close()
  481. scanner := bufio.NewScanner(file)
  482. for scanner.Scan() {
  483. line := strings.TrimSpace(scanner.Text())
  484. if line == "" || strings.Contains(line, "api -> api") {
  485. //skipping empty lines and api calls
  486. continue
  487. }
  488. if filter != "" && !strings.Contains(line, filter) {
  489. //applying filter if it's not empty
  490. continue
  491. }
  492. var entry LogEntry
  493. parts := strings.Fields(line)
  494. for i, part := range parts {
  495. if i == 0 {
  496. dateTime, err := time.Parse("2006/01/02 15:04:05.999999", parts[0]+" "+parts[1])
  497. if err != nil {
  498. continue
  499. }
  500. entry.DateTime = dateTime
  501. }
  502. if part == "from" {
  503. entry.FromAddress = parts[i+1]
  504. } else if part == "accepted" {
  505. entry.ToAddress = parts[i+1]
  506. } else if strings.HasPrefix(part, "[") {
  507. entry.Inbound = part[1:]
  508. } else if strings.HasSuffix(part, "]") {
  509. entry.Outbound = part[:len(part)-1]
  510. } else if part == "email:" {
  511. entry.Email = parts[i+1]
  512. }
  513. }
  514. if logEntryContains(line, freedoms) {
  515. if showDirect == "false" {
  516. continue
  517. }
  518. entry.Event = Direct
  519. } else if logEntryContains(line, blackholes) {
  520. if showBlocked == "false" {
  521. continue
  522. }
  523. entry.Event = Blocked
  524. } else {
  525. if showProxy == "false" {
  526. continue
  527. }
  528. entry.Event = Proxied
  529. }
  530. entries = append(entries, entry)
  531. }
  532. if len(entries) > countInt {
  533. entries = entries[len(entries)-countInt:]
  534. }
  535. return entries
  536. }
  537. func logEntryContains(line string, suffixes []string) bool {
  538. for _, sfx := range suffixes {
  539. if strings.Contains(line, sfx+"]") {
  540. return true
  541. }
  542. }
  543. return false
  544. }
  545. func (s *ServerService) GetConfigJson() (any, error) {
  546. config, err := s.xrayService.GetXrayConfig()
  547. if err != nil {
  548. return nil, err
  549. }
  550. contents, err := json.MarshalIndent(config, "", " ")
  551. if err != nil {
  552. return nil, err
  553. }
  554. var jsonData any
  555. err = json.Unmarshal(contents, &jsonData)
  556. if err != nil {
  557. return nil, err
  558. }
  559. return jsonData, nil
  560. }
  561. func (s *ServerService) GetDb() ([]byte, error) {
  562. // Update by manually trigger a checkpoint operation
  563. err := database.Checkpoint()
  564. if err != nil {
  565. return nil, err
  566. }
  567. // Open the file for reading
  568. file, err := os.Open(config.GetDBPath())
  569. if err != nil {
  570. return nil, err
  571. }
  572. defer file.Close()
  573. // Read the file contents
  574. fileContents, err := io.ReadAll(file)
  575. if err != nil {
  576. return nil, err
  577. }
  578. return fileContents, nil
  579. }
  580. func (s *ServerService) ImportDB(file multipart.File) error {
  581. // Check if the file is a SQLite database
  582. isValidDb, err := database.IsSQLiteDB(file)
  583. if err != nil {
  584. return common.NewErrorf("Error checking db file format: %v", err)
  585. }
  586. if !isValidDb {
  587. return common.NewError("Invalid db file format")
  588. }
  589. // Reset the file reader to the beginning
  590. _, err = file.Seek(0, 0)
  591. if err != nil {
  592. return common.NewErrorf("Error resetting file reader: %v", err)
  593. }
  594. // Save the file as a temporary file
  595. tempPath := fmt.Sprintf("%s.temp", config.GetDBPath())
  596. // Remove the existing temporary file (if any)
  597. if _, err := os.Stat(tempPath); err == nil {
  598. if errRemove := os.Remove(tempPath); errRemove != nil {
  599. return common.NewErrorf("Error removing existing temporary db file: %v", errRemove)
  600. }
  601. }
  602. // Create the temporary file
  603. tempFile, err := os.Create(tempPath)
  604. if err != nil {
  605. return common.NewErrorf("Error creating temporary db file: %v", err)
  606. }
  607. // Robust deferred cleanup for the temporary file
  608. defer func() {
  609. if tempFile != nil {
  610. if cerr := tempFile.Close(); cerr != nil {
  611. logger.Warningf("Warning: failed to close temp file: %v", cerr)
  612. }
  613. }
  614. if _, err := os.Stat(tempPath); err == nil {
  615. if rerr := os.Remove(tempPath); rerr != nil {
  616. logger.Warningf("Warning: failed to remove temp file: %v", rerr)
  617. }
  618. }
  619. }()
  620. // Save uploaded file to temporary file
  621. if _, err = io.Copy(tempFile, file); err != nil {
  622. return common.NewErrorf("Error saving db: %v", err)
  623. }
  624. // Check if we can init the db or not
  625. if err = database.InitDB(tempPath); err != nil {
  626. return common.NewErrorf("Error checking db: %v", err)
  627. }
  628. // Stop Xray
  629. s.StopXrayService()
  630. // Backup the current database for fallback
  631. fallbackPath := fmt.Sprintf("%s.backup", config.GetDBPath())
  632. // Remove the existing fallback file (if any)
  633. if _, err := os.Stat(fallbackPath); err == nil {
  634. if errRemove := os.Remove(fallbackPath); errRemove != nil {
  635. return common.NewErrorf("Error removing existing fallback db file: %v", errRemove)
  636. }
  637. }
  638. // Move the current database to the fallback location
  639. if err = os.Rename(config.GetDBPath(), fallbackPath); err != nil {
  640. return common.NewErrorf("Error backing up current db file: %v", err)
  641. }
  642. // Defer fallback cleanup ONLY if everything goes well
  643. defer func() {
  644. if _, err := os.Stat(fallbackPath); err == nil {
  645. if rerr := os.Remove(fallbackPath); rerr != nil {
  646. logger.Warningf("Warning: failed to remove fallback file: %v", rerr)
  647. }
  648. }
  649. }()
  650. // Move temp to DB path
  651. if err = os.Rename(tempPath, config.GetDBPath()); err != nil {
  652. // Restore from fallback
  653. if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
  654. return common.NewErrorf("Error moving db file and restoring fallback: %v", errRename)
  655. }
  656. return common.NewErrorf("Error moving db file: %v", err)
  657. }
  658. // Migrate DB
  659. if err = database.InitDB(config.GetDBPath()); err != nil {
  660. if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
  661. return common.NewErrorf("Error migrating db and restoring fallback: %v", errRename)
  662. }
  663. return common.NewErrorf("Error migrating db: %v", err)
  664. }
  665. s.inboundService.MigrateDB()
  666. // Start Xray
  667. if err = s.RestartXrayService(); err != nil {
  668. return common.NewErrorf("Imported DB but failed to start Xray: %v", err)
  669. }
  670. return nil
  671. }
  672. func (s *ServerService) UpdateGeofile(fileName string) error {
  673. files := []struct {
  674. URL string
  675. FileName string
  676. }{
  677. {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip.dat"},
  678. {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite.dat"},
  679. {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geoip.dat", "geoip_IR.dat"},
  680. {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat", "geosite_IR.dat"},
  681. {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip_RU.dat"},
  682. {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite_RU.dat"},
  683. }
  684. downloadFile := func(url, destPath string) error {
  685. resp, err := http.Get(url)
  686. if err != nil {
  687. return common.NewErrorf("Failed to download Geofile from %s: %v", url, err)
  688. }
  689. defer resp.Body.Close()
  690. file, err := os.Create(destPath)
  691. if err != nil {
  692. return common.NewErrorf("Failed to create Geofile %s: %v", destPath, err)
  693. }
  694. defer file.Close()
  695. _, err = io.Copy(file, resp.Body)
  696. if err != nil {
  697. return common.NewErrorf("Failed to save Geofile %s: %v", destPath, err)
  698. }
  699. return nil
  700. }
  701. var errorMessages []string
  702. if fileName == "" {
  703. for _, file := range files {
  704. destPath := fmt.Sprintf("%s/%s", config.GetBinFolderPath(), file.FileName)
  705. if err := downloadFile(file.URL, destPath); err != nil {
  706. errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", file.FileName, err))
  707. }
  708. }
  709. } else {
  710. destPath := fmt.Sprintf("%s/%s", config.GetBinFolderPath(), fileName)
  711. var fileURL string
  712. for _, file := range files {
  713. if file.FileName == fileName {
  714. fileURL = file.URL
  715. break
  716. }
  717. }
  718. if fileURL == "" {
  719. errorMessages = append(errorMessages, fmt.Sprintf("File '%s' not found in the list of Geofiles", fileName))
  720. }
  721. if err := downloadFile(fileURL, destPath); err != nil {
  722. errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", fileName, err))
  723. }
  724. }
  725. err := s.RestartXrayService()
  726. if err != nil {
  727. errorMessages = append(errorMessages, fmt.Sprintf("Updated Geofile '%s' but Failed to start Xray: %v", fileName, err))
  728. }
  729. if len(errorMessages) > 0 {
  730. return common.NewErrorf("%s", strings.Join(errorMessages, "\r\n"))
  731. }
  732. return nil
  733. }
  734. func (s *ServerService) GetNewX25519Cert() (any, error) {
  735. // Run the command
  736. cmd := exec.Command(xray.GetBinaryPath(), "x25519")
  737. var out bytes.Buffer
  738. cmd.Stdout = &out
  739. err := cmd.Run()
  740. if err != nil {
  741. return nil, err
  742. }
  743. lines := strings.Split(out.String(), "\n")
  744. privateKeyLine := strings.Split(lines[0], ":")
  745. publicKeyLine := strings.Split(lines[1], ":")
  746. privateKey := strings.TrimSpace(privateKeyLine[1])
  747. publicKey := strings.TrimSpace(publicKeyLine[1])
  748. keyPair := map[string]any{
  749. "privateKey": privateKey,
  750. "publicKey": publicKey,
  751. }
  752. return keyPair, nil
  753. }
  754. func (s *ServerService) GetNewmldsa65() (any, error) {
  755. // Run the command
  756. cmd := exec.Command(xray.GetBinaryPath(), "mldsa65")
  757. var out bytes.Buffer
  758. cmd.Stdout = &out
  759. err := cmd.Run()
  760. if err != nil {
  761. return nil, err
  762. }
  763. lines := strings.Split(out.String(), "\n")
  764. SeedLine := strings.Split(lines[0], ":")
  765. VerifyLine := strings.Split(lines[1], ":")
  766. seed := strings.TrimSpace(SeedLine[1])
  767. verify := strings.TrimSpace(VerifyLine[1])
  768. keyPair := map[string]any{
  769. "seed": seed,
  770. "verify": verify,
  771. }
  772. return keyPair, nil
  773. }
  774. func (s *ServerService) GetNewEchCert(sni string) (interface{}, error) {
  775. // Run the command
  776. cmd := exec.Command(xray.GetBinaryPath(), "tls", "ech", "--serverName", sni)
  777. var out bytes.Buffer
  778. cmd.Stdout = &out
  779. err := cmd.Run()
  780. if err != nil {
  781. return nil, err
  782. }
  783. lines := strings.Split(out.String(), "\n")
  784. if len(lines) < 4 {
  785. return nil, common.NewError("invalid ech cert")
  786. }
  787. configList := lines[1]
  788. serverKeys := lines[3]
  789. return map[string]interface{}{
  790. "echServerKeys": serverKeys,
  791. "echConfigList": configList,
  792. }, nil
  793. }
  794. func (s *ServerService) GetNewVlessEnc() (any, error) {
  795. cmd := exec.Command(xray.GetBinaryPath(), "vlessenc")
  796. var out bytes.Buffer
  797. cmd.Stdout = &out
  798. if err := cmd.Run(); err != nil {
  799. return nil, err
  800. }
  801. lines := strings.Split(out.String(), "\n")
  802. var auths []map[string]string
  803. var current map[string]string
  804. for _, line := range lines {
  805. line = strings.TrimSpace(line)
  806. if strings.HasPrefix(line, "Authentication:") {
  807. if current != nil {
  808. auths = append(auths, current)
  809. }
  810. current = map[string]string{
  811. "label": strings.TrimSpace(strings.TrimPrefix(line, "Authentication:")),
  812. }
  813. } else if strings.HasPrefix(line, `"decryption"`) || strings.HasPrefix(line, `"encryption"`) {
  814. parts := strings.SplitN(line, ":", 2)
  815. if len(parts) == 2 && current != nil {
  816. key := strings.Trim(parts[0], `" `)
  817. val := strings.Trim(parts[1], `" `)
  818. current[key] = val
  819. }
  820. }
  821. }
  822. if current != nil {
  823. auths = append(auths, current)
  824. }
  825. return map[string]any{
  826. "auths": auths,
  827. }, nil
  828. }
  829. func (s *ServerService) GetNewUUID() (map[string]string, error) {
  830. newUUID, err := uuid.NewRandom()
  831. if err != nil {
  832. return nil, fmt.Errorf("failed to generate UUID: %w", err)
  833. }
  834. return map[string]string{
  835. "uuid": newUUID.String(),
  836. }, nil
  837. }
  838. func (s *ServerService) GetNewmlkem768() (any, error) {
  839. // Run the command
  840. cmd := exec.Command(xray.GetBinaryPath(), "mlkem768")
  841. var out bytes.Buffer
  842. cmd.Stdout = &out
  843. err := cmd.Run()
  844. if err != nil {
  845. return nil, err
  846. }
  847. lines := strings.Split(out.String(), "\n")
  848. SeedLine := strings.Split(lines[0], ":")
  849. ClientLine := strings.Split(lines[1], ":")
  850. seed := strings.TrimSpace(SeedLine[1])
  851. client := strings.TrimSpace(ClientLine[1])
  852. keyPair := map[string]any{
  853. "seed": seed,
  854. "client": client,
  855. }
  856. return keyPair, nil
  857. }