server.go 20 KB

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