server.go 18 KB

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