server.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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 > 8) || (major == 25 && minor == 8 && patch >= 3) {
  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. err := s.xrayService.RestartXray(true)
  306. if err != nil {
  307. logger.Error("start xray failed:", err)
  308. return err
  309. }
  310. return nil
  311. }
  312. func (s *ServerService) downloadXRay(version string) (string, error) {
  313. osName := runtime.GOOS
  314. arch := runtime.GOARCH
  315. switch osName {
  316. case "darwin":
  317. osName = "macos"
  318. }
  319. switch arch {
  320. case "amd64":
  321. arch = "64"
  322. case "arm64":
  323. arch = "arm64-v8a"
  324. case "armv7":
  325. arch = "arm32-v7a"
  326. case "armv6":
  327. arch = "arm32-v6"
  328. case "armv5":
  329. arch = "arm32-v5"
  330. case "386":
  331. arch = "32"
  332. case "s390x":
  333. arch = "s390x"
  334. }
  335. fileName := fmt.Sprintf("Xray-%s-%s.zip", osName, arch)
  336. url := fmt.Sprintf("https://github.com/XTLS/Xray-core/releases/download/%s/%s", version, fileName)
  337. resp, err := http.Get(url)
  338. if err != nil {
  339. return "", err
  340. }
  341. defer resp.Body.Close()
  342. os.Remove(fileName)
  343. file, err := os.Create(fileName)
  344. if err != nil {
  345. return "", err
  346. }
  347. defer file.Close()
  348. _, err = io.Copy(file, resp.Body)
  349. if err != nil {
  350. return "", err
  351. }
  352. return fileName, nil
  353. }
  354. func (s *ServerService) UpdateXray(version string) error {
  355. zipFileName, err := s.downloadXRay(version)
  356. if err != nil {
  357. return err
  358. }
  359. zipFile, err := os.Open(zipFileName)
  360. if err != nil {
  361. return err
  362. }
  363. defer func() {
  364. zipFile.Close()
  365. os.Remove(zipFileName)
  366. }()
  367. stat, err := zipFile.Stat()
  368. if err != nil {
  369. return err
  370. }
  371. reader, err := zip.NewReader(zipFile, stat.Size())
  372. if err != nil {
  373. return err
  374. }
  375. s.xrayService.StopXray()
  376. defer func() {
  377. err := s.xrayService.RestartXray(true)
  378. if err != nil {
  379. logger.Error("start xray failed:", err)
  380. }
  381. }()
  382. copyZipFile := func(zipName string, fileName string) error {
  383. zipFile, err := reader.Open(zipName)
  384. if err != nil {
  385. return err
  386. }
  387. os.Remove(fileName)
  388. file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, fs.ModePerm)
  389. if err != nil {
  390. return err
  391. }
  392. defer file.Close()
  393. _, err = io.Copy(file, zipFile)
  394. return err
  395. }
  396. err = copyZipFile("xray", xray.GetBinaryPath())
  397. if err != nil {
  398. return err
  399. }
  400. return nil
  401. }
  402. func (s *ServerService) GetLogs(count string, level string, syslog string) []string {
  403. c, _ := strconv.Atoi(count)
  404. var lines []string
  405. if syslog == "true" {
  406. cmdArgs := []string{"journalctl", "-u", "x-ui", "--no-pager", "-n", count, "-p", level}
  407. // Run the command
  408. cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
  409. var out bytes.Buffer
  410. cmd.Stdout = &out
  411. err := cmd.Run()
  412. if err != nil {
  413. return []string{"Failed to run journalctl command!"}
  414. }
  415. lines = strings.Split(out.String(), "\n")
  416. } else {
  417. lines = logger.GetLogs(c, level)
  418. }
  419. return lines
  420. }
  421. func (s *ServerService) GetXrayLogs(
  422. count string,
  423. filter string,
  424. showDirect string,
  425. showBlocked string,
  426. showProxy string,
  427. freedoms []string,
  428. blackholes []string) []string {
  429. countInt, _ := strconv.Atoi(count)
  430. var lines []string
  431. pathToAccessLog, err := xray.GetAccessLogPath()
  432. if err != nil {
  433. return lines
  434. }
  435. file, err := os.Open(pathToAccessLog)
  436. if err != nil {
  437. return lines
  438. }
  439. defer file.Close()
  440. scanner := bufio.NewScanner(file)
  441. for scanner.Scan() {
  442. line := strings.TrimSpace(scanner.Text())
  443. if line == "" || strings.Contains(line, "api -> api") {
  444. //skipping empty lines and api calls
  445. continue
  446. }
  447. if filter != "" && !strings.Contains(line, filter) {
  448. //applying filter if it's not empty
  449. continue
  450. }
  451. //adding suffixes to further distinguish entries by outbound
  452. if hasSuffix(line, freedoms) {
  453. if showDirect == "false" {
  454. continue
  455. }
  456. line = line + " f"
  457. } else if hasSuffix(line, blackholes) {
  458. if showBlocked == "false" {
  459. continue
  460. }
  461. line = line + " b"
  462. } else {
  463. if showProxy == "false" {
  464. continue
  465. }
  466. line = line + " p"
  467. }
  468. lines = append(lines, line)
  469. }
  470. if len(lines) > countInt {
  471. lines = lines[len(lines)-countInt:]
  472. }
  473. return lines
  474. }
  475. func hasSuffix(line string, suffixes []string) bool {
  476. for _, sfx := range suffixes {
  477. if strings.HasSuffix(line, sfx+"]") {
  478. return true
  479. }
  480. }
  481. return false
  482. }
  483. func (s *ServerService) GetConfigJson() (any, error) {
  484. config, err := s.xrayService.GetXrayConfig()
  485. if err != nil {
  486. return nil, err
  487. }
  488. contents, err := json.MarshalIndent(config, "", " ")
  489. if err != nil {
  490. return nil, err
  491. }
  492. var jsonData any
  493. err = json.Unmarshal(contents, &jsonData)
  494. if err != nil {
  495. return nil, err
  496. }
  497. return jsonData, nil
  498. }
  499. func (s *ServerService) GetDb() ([]byte, error) {
  500. // Update by manually trigger a checkpoint operation
  501. err := database.Checkpoint()
  502. if err != nil {
  503. return nil, err
  504. }
  505. // Open the file for reading
  506. file, err := os.Open(config.GetDBPath())
  507. if err != nil {
  508. return nil, err
  509. }
  510. defer file.Close()
  511. // Read the file contents
  512. fileContents, err := io.ReadAll(file)
  513. if err != nil {
  514. return nil, err
  515. }
  516. return fileContents, nil
  517. }
  518. func (s *ServerService) ImportDB(file multipart.File) error {
  519. // Check if the file is a SQLite database
  520. isValidDb, err := database.IsSQLiteDB(file)
  521. if err != nil {
  522. return common.NewErrorf("Error checking db file format: %v", err)
  523. }
  524. if !isValidDb {
  525. return common.NewError("Invalid db file format")
  526. }
  527. // Reset the file reader to the beginning
  528. _, err = file.Seek(0, 0)
  529. if err != nil {
  530. return common.NewErrorf("Error resetting file reader: %v", err)
  531. }
  532. // Save the file as a temporary file
  533. tempPath := fmt.Sprintf("%s.temp", config.GetDBPath())
  534. // Remove the existing temporary file (if any)
  535. if _, err := os.Stat(tempPath); err == nil {
  536. if errRemove := os.Remove(tempPath); errRemove != nil {
  537. return common.NewErrorf("Error removing existing temporary db file: %v", errRemove)
  538. }
  539. }
  540. // Create the temporary file
  541. tempFile, err := os.Create(tempPath)
  542. if err != nil {
  543. return common.NewErrorf("Error creating temporary db file: %v", err)
  544. }
  545. // Robust deferred cleanup for the temporary file
  546. defer func() {
  547. if tempFile != nil {
  548. if cerr := tempFile.Close(); cerr != nil {
  549. logger.Warningf("Warning: failed to close temp file: %v", cerr)
  550. }
  551. }
  552. if _, err := os.Stat(tempPath); err == nil {
  553. if rerr := os.Remove(tempPath); rerr != nil {
  554. logger.Warningf("Warning: failed to remove temp file: %v", rerr)
  555. }
  556. }
  557. }()
  558. // Save uploaded file to temporary file
  559. if _, err = io.Copy(tempFile, file); err != nil {
  560. return common.NewErrorf("Error saving db: %v", err)
  561. }
  562. // Check if we can init the db or not
  563. if err = database.InitDB(tempPath); err != nil {
  564. return common.NewErrorf("Error checking db: %v", err)
  565. }
  566. // Stop Xray
  567. s.StopXrayService()
  568. // Backup the current database for fallback
  569. fallbackPath := fmt.Sprintf("%s.backup", config.GetDBPath())
  570. // Remove the existing fallback file (if any)
  571. if _, err := os.Stat(fallbackPath); err == nil {
  572. if errRemove := os.Remove(fallbackPath); errRemove != nil {
  573. return common.NewErrorf("Error removing existing fallback db file: %v", errRemove)
  574. }
  575. }
  576. // Move the current database to the fallback location
  577. if err = os.Rename(config.GetDBPath(), fallbackPath); err != nil {
  578. return common.NewErrorf("Error backing up current db file: %v", err)
  579. }
  580. // Defer fallback cleanup ONLY if everything goes well
  581. defer func() {
  582. if _, err := os.Stat(fallbackPath); err == nil {
  583. if rerr := os.Remove(fallbackPath); rerr != nil {
  584. logger.Warningf("Warning: failed to remove fallback file: %v", rerr)
  585. }
  586. }
  587. }()
  588. // Move temp to DB path
  589. if err = os.Rename(tempPath, config.GetDBPath()); err != nil {
  590. // Restore from fallback
  591. if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
  592. return common.NewErrorf("Error moving db file and restoring fallback: %v", errRename)
  593. }
  594. return common.NewErrorf("Error moving db file: %v", err)
  595. }
  596. // Migrate DB
  597. if err = database.InitDB(config.GetDBPath()); err != nil {
  598. if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
  599. return common.NewErrorf("Error migrating db and restoring fallback: %v", errRename)
  600. }
  601. return common.NewErrorf("Error migrating db: %v", err)
  602. }
  603. s.inboundService.MigrateDB()
  604. // Start Xray
  605. if err = s.RestartXrayService(); err != nil {
  606. return common.NewErrorf("Imported DB but failed to start Xray: %v", err)
  607. }
  608. return nil
  609. }
  610. func (s *ServerService) UpdateGeofile(fileName string) error {
  611. files := []struct {
  612. URL string
  613. FileName string
  614. }{
  615. {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip.dat"},
  616. {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite.dat"},
  617. {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geoip.dat", "geoip_IR.dat"},
  618. {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat", "geosite_IR.dat"},
  619. {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip_RU.dat"},
  620. {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite_RU.dat"},
  621. }
  622. downloadFile := func(url, destPath string) error {
  623. resp, err := http.Get(url)
  624. if err != nil {
  625. return common.NewErrorf("Failed to download Geofile from %s: %v", url, err)
  626. }
  627. defer resp.Body.Close()
  628. file, err := os.Create(destPath)
  629. if err != nil {
  630. return common.NewErrorf("Failed to create Geofile %s: %v", destPath, err)
  631. }
  632. defer file.Close()
  633. _, err = io.Copy(file, resp.Body)
  634. if err != nil {
  635. return common.NewErrorf("Failed to save Geofile %s: %v", destPath, err)
  636. }
  637. return nil
  638. }
  639. var errorMessages []string
  640. if fileName == "" {
  641. for _, file := range files {
  642. destPath := fmt.Sprintf("%s/%s", config.GetBinFolderPath(), file.FileName)
  643. if err := downloadFile(file.URL, destPath); err != nil {
  644. errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", file.FileName, err))
  645. }
  646. }
  647. } else {
  648. destPath := fmt.Sprintf("%s/%s", config.GetBinFolderPath(), fileName)
  649. var fileURL string
  650. for _, file := range files {
  651. if file.FileName == fileName {
  652. fileURL = file.URL
  653. break
  654. }
  655. }
  656. if fileURL == "" {
  657. errorMessages = append(errorMessages, fmt.Sprintf("File '%s' not found in the list of Geofiles", fileName))
  658. }
  659. if err := downloadFile(fileURL, destPath); err != nil {
  660. errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", fileName, err))
  661. }
  662. }
  663. err := s.RestartXrayService()
  664. if err != nil {
  665. errorMessages = append(errorMessages, fmt.Sprintf("Updated Geofile '%s' but Failed to start Xray: %v", fileName, err))
  666. }
  667. if len(errorMessages) > 0 {
  668. return common.NewErrorf("%s", strings.Join(errorMessages, "\r\n"))
  669. }
  670. return nil
  671. }
  672. func (s *ServerService) GetNewX25519Cert() (any, error) {
  673. // Run the command
  674. cmd := exec.Command(xray.GetBinaryPath(), "x25519")
  675. var out bytes.Buffer
  676. cmd.Stdout = &out
  677. err := cmd.Run()
  678. if err != nil {
  679. return nil, err
  680. }
  681. lines := strings.Split(out.String(), "\n")
  682. privateKeyLine := strings.Split(lines[0], ":")
  683. publicKeyLine := strings.Split(lines[1], ":")
  684. privateKey := strings.TrimSpace(privateKeyLine[1])
  685. publicKey := strings.TrimSpace(publicKeyLine[1])
  686. keyPair := map[string]any{
  687. "privateKey": privateKey,
  688. "publicKey": publicKey,
  689. }
  690. return keyPair, nil
  691. }
  692. func (s *ServerService) GetNewmldsa65() (any, error) {
  693. // Run the command
  694. cmd := exec.Command(xray.GetBinaryPath(), "mldsa65")
  695. var out bytes.Buffer
  696. cmd.Stdout = &out
  697. err := cmd.Run()
  698. if err != nil {
  699. return nil, err
  700. }
  701. lines := strings.Split(out.String(), "\n")
  702. SeedLine := strings.Split(lines[0], ":")
  703. VerifyLine := strings.Split(lines[1], ":")
  704. seed := strings.TrimSpace(SeedLine[1])
  705. verify := strings.TrimSpace(VerifyLine[1])
  706. keyPair := map[string]any{
  707. "seed": seed,
  708. "verify": verify,
  709. }
  710. return keyPair, nil
  711. }
  712. func (s *ServerService) GetNewEchCert(sni string) (interface{}, error) {
  713. // Run the command
  714. cmd := exec.Command(xray.GetBinaryPath(), "tls", "ech", "--serverName", sni)
  715. var out bytes.Buffer
  716. cmd.Stdout = &out
  717. err := cmd.Run()
  718. if err != nil {
  719. return nil, err
  720. }
  721. lines := strings.Split(out.String(), "\n")
  722. if len(lines) < 4 {
  723. return nil, common.NewError("invalid ech cert")
  724. }
  725. configList := lines[1]
  726. serverKeys := lines[3]
  727. return map[string]interface{}{
  728. "echServerKeys": serverKeys,
  729. "echConfigList": configList,
  730. }, nil
  731. }