server.go 27 KB

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