server.go 26 KB

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