server.go 28 KB

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