server.go 22 KB

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