server.go 22 KB

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