server.go 27 KB

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