server.go 28 KB

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