server.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  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. 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(
  423. count string,
  424. filter string,
  425. showDirect string,
  426. showBlocked string,
  427. showProxy string,
  428. freedoms []string,
  429. blackholes []string) []string {
  430. countInt, _ := strconv.Atoi(count)
  431. var lines []string
  432. pathToAccessLog, err := xray.GetAccessLogPath()
  433. if err != nil {
  434. return lines
  435. }
  436. file, err := os.Open(pathToAccessLog)
  437. if err != nil {
  438. return lines
  439. }
  440. defer file.Close()
  441. scanner := bufio.NewScanner(file)
  442. for scanner.Scan() {
  443. line := strings.TrimSpace(scanner.Text())
  444. if line == "" || strings.Contains(line, "api -> api") {
  445. //skipping empty lines and api calls
  446. continue
  447. }
  448. if filter != "" && !strings.Contains(line, filter) {
  449. //applying filter if it's not empty
  450. continue
  451. }
  452. //adding suffixes to further distinguish entries by outbound
  453. if hasSuffix(line, freedoms) {
  454. if showDirect == "false" {
  455. continue
  456. }
  457. line = line + " f"
  458. } else if hasSuffix(line, blackholes) {
  459. if showBlocked == "false" {
  460. continue
  461. }
  462. line = line + " b"
  463. } else {
  464. if showProxy == "false" {
  465. continue
  466. }
  467. line = line + " p"
  468. }
  469. lines = append(lines, line)
  470. }
  471. if len(lines) > countInt {
  472. lines = lines[len(lines)-countInt:]
  473. }
  474. return lines
  475. }
  476. func hasSuffix(line string, suffixes []string) bool {
  477. for _, sfx := range suffixes {
  478. if strings.HasSuffix(line, sfx+"]") {
  479. return true
  480. }
  481. }
  482. return false
  483. }
  484. func (s *ServerService) GetConfigJson() (any, error) {
  485. config, err := s.xrayService.GetXrayConfig()
  486. if err != nil {
  487. return nil, err
  488. }
  489. contents, err := json.MarshalIndent(config, "", " ")
  490. if err != nil {
  491. return nil, err
  492. }
  493. var jsonData any
  494. err = json.Unmarshal(contents, &jsonData)
  495. if err != nil {
  496. return nil, err
  497. }
  498. return jsonData, nil
  499. }
  500. func (s *ServerService) GetDb() ([]byte, error) {
  501. // Update by manually trigger a checkpoint operation
  502. err := database.Checkpoint()
  503. if err != nil {
  504. return nil, err
  505. }
  506. // Open the file for reading
  507. file, err := os.Open(config.GetDBPath())
  508. if err != nil {
  509. return nil, err
  510. }
  511. defer file.Close()
  512. // Read the file contents
  513. fileContents, err := io.ReadAll(file)
  514. if err != nil {
  515. return nil, err
  516. }
  517. return fileContents, nil
  518. }
  519. func (s *ServerService) ImportDB(file multipart.File) error {
  520. // Check if the file is a SQLite database
  521. isValidDb, err := database.IsSQLiteDB(file)
  522. if err != nil {
  523. return common.NewErrorf("Error checking db file format: %v", err)
  524. }
  525. if !isValidDb {
  526. return common.NewError("Invalid db file format")
  527. }
  528. // Reset the file reader to the beginning
  529. _, err = file.Seek(0, 0)
  530. if err != nil {
  531. return common.NewErrorf("Error resetting file reader: %v", err)
  532. }
  533. // Save the file as a temporary file
  534. tempPath := fmt.Sprintf("%s.temp", config.GetDBPath())
  535. // Remove the existing temporary file (if any)
  536. if _, err := os.Stat(tempPath); err == nil {
  537. if errRemove := os.Remove(tempPath); errRemove != nil {
  538. return common.NewErrorf("Error removing existing temporary db file: %v", errRemove)
  539. }
  540. }
  541. // Create the temporary file
  542. tempFile, err := os.Create(tempPath)
  543. if err != nil {
  544. return common.NewErrorf("Error creating temporary db file: %v", err)
  545. }
  546. // Robust deferred cleanup for the temporary file
  547. defer func() {
  548. if tempFile != nil {
  549. if cerr := tempFile.Close(); cerr != nil {
  550. logger.Warningf("Warning: failed to close temp file: %v", cerr)
  551. }
  552. }
  553. if _, err := os.Stat(tempPath); err == nil {
  554. if rerr := os.Remove(tempPath); rerr != nil {
  555. logger.Warningf("Warning: failed to remove temp file: %v", rerr)
  556. }
  557. }
  558. }()
  559. // Save uploaded file to temporary file
  560. if _, err = io.Copy(tempFile, file); err != nil {
  561. return common.NewErrorf("Error saving db: %v", err)
  562. }
  563. // Check if we can init the db or not
  564. if err = database.InitDB(tempPath); err != nil {
  565. return common.NewErrorf("Error checking db: %v", err)
  566. }
  567. // Stop Xray
  568. s.StopXrayService()
  569. // Backup the current database for fallback
  570. fallbackPath := fmt.Sprintf("%s.backup", config.GetDBPath())
  571. // Remove the existing fallback file (if any)
  572. if _, err := os.Stat(fallbackPath); err == nil {
  573. if errRemove := os.Remove(fallbackPath); errRemove != nil {
  574. return common.NewErrorf("Error removing existing fallback db file: %v", errRemove)
  575. }
  576. }
  577. // Move the current database to the fallback location
  578. if err = os.Rename(config.GetDBPath(), fallbackPath); err != nil {
  579. return common.NewErrorf("Error backing up current db file: %v", err)
  580. }
  581. // Defer fallback cleanup ONLY if everything goes well
  582. defer func() {
  583. if _, err := os.Stat(fallbackPath); err == nil {
  584. if rerr := os.Remove(fallbackPath); rerr != nil {
  585. logger.Warningf("Warning: failed to remove fallback file: %v", rerr)
  586. }
  587. }
  588. }()
  589. // Move temp to DB path
  590. if err = os.Rename(tempPath, config.GetDBPath()); err != nil {
  591. // Restore from fallback
  592. if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
  593. return common.NewErrorf("Error moving db file and restoring fallback: %v", errRename)
  594. }
  595. return common.NewErrorf("Error moving db file: %v", err)
  596. }
  597. // Migrate DB
  598. if err = database.InitDB(config.GetDBPath()); err != nil {
  599. if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
  600. return common.NewErrorf("Error migrating db and restoring fallback: %v", errRename)
  601. }
  602. return common.NewErrorf("Error migrating db: %v", err)
  603. }
  604. s.inboundService.MigrateDB()
  605. // Start Xray
  606. if err = s.RestartXrayService(); err != nil {
  607. return common.NewErrorf("Imported DB but failed to start Xray: %v", err)
  608. }
  609. return nil
  610. }
  611. func (s *ServerService) UpdateGeofile(fileName string) error {
  612. files := []struct {
  613. URL string
  614. FileName string
  615. }{
  616. {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip.dat"},
  617. {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite.dat"},
  618. {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geoip.dat", "geoip_IR.dat"},
  619. {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat", "geosite_IR.dat"},
  620. {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip_RU.dat"},
  621. {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite_RU.dat"},
  622. }
  623. downloadFile := func(url, destPath string) error {
  624. resp, err := http.Get(url)
  625. if err != nil {
  626. return common.NewErrorf("Failed to download Geofile from %s: %v", url, err)
  627. }
  628. defer resp.Body.Close()
  629. file, err := os.Create(destPath)
  630. if err != nil {
  631. return common.NewErrorf("Failed to create Geofile %s: %v", destPath, err)
  632. }
  633. defer file.Close()
  634. _, err = io.Copy(file, resp.Body)
  635. if err != nil {
  636. return common.NewErrorf("Failed to save Geofile %s: %v", destPath, err)
  637. }
  638. return nil
  639. }
  640. var errorMessages []string
  641. if fileName == "" {
  642. for _, file := range files {
  643. destPath := fmt.Sprintf("%s/%s", config.GetBinFolderPath(), file.FileName)
  644. if err := downloadFile(file.URL, destPath); err != nil {
  645. errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", file.FileName, err))
  646. }
  647. }
  648. } else {
  649. destPath := fmt.Sprintf("%s/%s", config.GetBinFolderPath(), fileName)
  650. var fileURL string
  651. for _, file := range files {
  652. if file.FileName == fileName {
  653. fileURL = file.URL
  654. break
  655. }
  656. }
  657. if fileURL == "" {
  658. errorMessages = append(errorMessages, fmt.Sprintf("File '%s' not found in the list of Geofiles", fileName))
  659. }
  660. if err := downloadFile(fileURL, destPath); err != nil {
  661. errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", fileName, err))
  662. }
  663. }
  664. err := s.RestartXrayService()
  665. if err != nil {
  666. errorMessages = append(errorMessages, fmt.Sprintf("Updated Geofile '%s' but Failed to start Xray: %v", fileName, err))
  667. }
  668. if len(errorMessages) > 0 {
  669. return common.NewErrorf("%s", strings.Join(errorMessages, "\r\n"))
  670. }
  671. return nil
  672. }
  673. func (s *ServerService) GetNewX25519Cert() (any, error) {
  674. // Run the command
  675. cmd := exec.Command(xray.GetBinaryPath(), "x25519")
  676. var out bytes.Buffer
  677. cmd.Stdout = &out
  678. err := cmd.Run()
  679. if err != nil {
  680. return nil, err
  681. }
  682. lines := strings.Split(out.String(), "\n")
  683. privateKeyLine := strings.Split(lines[0], ":")
  684. publicKeyLine := strings.Split(lines[1], ":")
  685. privateKey := strings.TrimSpace(privateKeyLine[1])
  686. publicKey := strings.TrimSpace(publicKeyLine[1])
  687. keyPair := map[string]any{
  688. "privateKey": privateKey,
  689. "publicKey": publicKey,
  690. }
  691. return keyPair, nil
  692. }
  693. func (s *ServerService) GetNewmldsa65() (any, error) {
  694. // Run the command
  695. cmd := exec.Command(xray.GetBinaryPath(), "mldsa65")
  696. var out bytes.Buffer
  697. cmd.Stdout = &out
  698. err := cmd.Run()
  699. if err != nil {
  700. return nil, err
  701. }
  702. lines := strings.Split(out.String(), "\n")
  703. SeedLine := strings.Split(lines[0], ":")
  704. VerifyLine := strings.Split(lines[1], ":")
  705. seed := strings.TrimSpace(SeedLine[1])
  706. verify := strings.TrimSpace(VerifyLine[1])
  707. keyPair := map[string]any{
  708. "seed": seed,
  709. "verify": verify,
  710. }
  711. return keyPair, nil
  712. }
  713. func (s *ServerService) GetNewEchCert(sni string) (interface{}, error) {
  714. // Run the command
  715. cmd := exec.Command(xray.GetBinaryPath(), "tls", "ech", "--serverName", sni)
  716. var out bytes.Buffer
  717. cmd.Stdout = &out
  718. err := cmd.Run()
  719. if err != nil {
  720. return nil, err
  721. }
  722. lines := strings.Split(out.String(), "\n")
  723. if len(lines) < 4 {
  724. return nil, common.NewError("invalid ech cert")
  725. }
  726. configList := lines[1]
  727. serverKeys := lines[3]
  728. return map[string]interface{}{
  729. "echServerKeys": serverKeys,
  730. "echConfigList": configList,
  731. }, nil
  732. }