server.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  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. // Check if running on Windows - journalctl is not available
  624. if runtime.GOOS == "windows" {
  625. return []string{"Syslog is not supported on Windows. Please use application logs instead by unchecking the 'Syslog' option."}
  626. }
  627. // Validate and sanitize count parameter
  628. countInt, err := strconv.Atoi(count)
  629. if err != nil || countInt < 1 || countInt > 10000 {
  630. return []string{"Invalid count parameter - must be a number between 1 and 10000"}
  631. }
  632. // Validate level parameter - only allow valid syslog levels
  633. validLevels := map[string]bool{
  634. "0": true, "emerg": true,
  635. "1": true, "alert": true,
  636. "2": true, "crit": true,
  637. "3": true, "err": true,
  638. "4": true, "warning": true,
  639. "5": true, "notice": true,
  640. "6": true, "info": true,
  641. "7": true, "debug": true,
  642. }
  643. if !validLevels[level] {
  644. return []string{"Invalid level parameter - must be a valid syslog level"}
  645. }
  646. // Use hardcoded command with validated parameters
  647. cmd := exec.Command("journalctl", "-u", "x-ui", "--no-pager", "-n", strconv.Itoa(countInt), "-p", level)
  648. var out bytes.Buffer
  649. cmd.Stdout = &out
  650. err = cmd.Run()
  651. if err != nil {
  652. return []string{"Failed to run journalctl command! Make sure systemd is available and x-ui service is registered."}
  653. }
  654. lines = strings.Split(out.String(), "\n")
  655. } else {
  656. lines = logger.GetLogs(c, level)
  657. }
  658. return lines
  659. }
  660. func (s *ServerService) GetXrayLogs(
  661. count string,
  662. filter string,
  663. showDirect string,
  664. showBlocked string,
  665. showProxy string,
  666. freedoms []string,
  667. blackholes []string) []LogEntry {
  668. const (
  669. Direct = iota
  670. Blocked
  671. Proxied
  672. )
  673. countInt, _ := strconv.Atoi(count)
  674. var entries []LogEntry
  675. pathToAccessLog, err := xray.GetAccessLogPath()
  676. if err != nil {
  677. return nil
  678. }
  679. file, err := os.Open(pathToAccessLog)
  680. if err != nil {
  681. return nil
  682. }
  683. defer file.Close()
  684. scanner := bufio.NewScanner(file)
  685. for scanner.Scan() {
  686. line := strings.TrimSpace(scanner.Text())
  687. if line == "" || strings.Contains(line, "api -> api") {
  688. //skipping empty lines and api calls
  689. continue
  690. }
  691. if filter != "" && !strings.Contains(line, filter) {
  692. //applying filter if it's not empty
  693. continue
  694. }
  695. var entry LogEntry
  696. parts := strings.Fields(line)
  697. for i, part := range parts {
  698. if i == 0 {
  699. dateTime, err := time.Parse("2006/01/02 15:04:05.999999", parts[0]+" "+parts[1])
  700. if err != nil {
  701. continue
  702. }
  703. entry.DateTime = dateTime
  704. }
  705. if part == "from" {
  706. entry.FromAddress = parts[i+1]
  707. } else if part == "accepted" {
  708. entry.ToAddress = parts[i+1]
  709. } else if strings.HasPrefix(part, "[") {
  710. entry.Inbound = part[1:]
  711. } else if strings.HasSuffix(part, "]") {
  712. entry.Outbound = part[:len(part)-1]
  713. } else if part == "email:" {
  714. entry.Email = parts[i+1]
  715. }
  716. }
  717. if logEntryContains(line, freedoms) {
  718. if showDirect == "false" {
  719. continue
  720. }
  721. entry.Event = Direct
  722. } else if logEntryContains(line, blackholes) {
  723. if showBlocked == "false" {
  724. continue
  725. }
  726. entry.Event = Blocked
  727. } else {
  728. if showProxy == "false" {
  729. continue
  730. }
  731. entry.Event = Proxied
  732. }
  733. entries = append(entries, entry)
  734. }
  735. if len(entries) > countInt {
  736. entries = entries[len(entries)-countInt:]
  737. }
  738. return entries
  739. }
  740. func logEntryContains(line string, suffixes []string) bool {
  741. for _, sfx := range suffixes {
  742. if strings.Contains(line, sfx+"]") {
  743. return true
  744. }
  745. }
  746. return false
  747. }
  748. func (s *ServerService) GetConfigJson() (any, error) {
  749. config, err := s.xrayService.GetXrayConfig()
  750. if err != nil {
  751. return nil, err
  752. }
  753. contents, err := json.MarshalIndent(config, "", " ")
  754. if err != nil {
  755. return nil, err
  756. }
  757. var jsonData any
  758. err = json.Unmarshal(contents, &jsonData)
  759. if err != nil {
  760. return nil, err
  761. }
  762. return jsonData, nil
  763. }
  764. func (s *ServerService) GetDb() ([]byte, error) {
  765. // Update by manually trigger a checkpoint operation
  766. err := database.Checkpoint()
  767. if err != nil {
  768. return nil, err
  769. }
  770. // Open the file for reading
  771. file, err := os.Open(config.GetDBPath())
  772. if err != nil {
  773. return nil, err
  774. }
  775. defer file.Close()
  776. // Read the file contents
  777. fileContents, err := io.ReadAll(file)
  778. if err != nil {
  779. return nil, err
  780. }
  781. return fileContents, nil
  782. }
  783. func (s *ServerService) ImportDB(file multipart.File) error {
  784. // Check if the file is a SQLite database
  785. isValidDb, err := database.IsSQLiteDB(file)
  786. if err != nil {
  787. return common.NewErrorf("Error checking db file format: %v", err)
  788. }
  789. if !isValidDb {
  790. return common.NewError("Invalid db file format")
  791. }
  792. // Reset the file reader to the beginning
  793. _, err = file.Seek(0, 0)
  794. if err != nil {
  795. return common.NewErrorf("Error resetting file reader: %v", err)
  796. }
  797. // Save the file as a temporary file
  798. tempPath := fmt.Sprintf("%s.temp", config.GetDBPath())
  799. // Remove the existing temporary file (if any)
  800. if _, err := os.Stat(tempPath); err == nil {
  801. if errRemove := os.Remove(tempPath); errRemove != nil {
  802. return common.NewErrorf("Error removing existing temporary db file: %v", errRemove)
  803. }
  804. }
  805. // Create the temporary file
  806. tempFile, err := os.Create(tempPath)
  807. if err != nil {
  808. return common.NewErrorf("Error creating temporary db file: %v", err)
  809. }
  810. // Robust deferred cleanup for the temporary file
  811. defer func() {
  812. if tempFile != nil {
  813. if cerr := tempFile.Close(); cerr != nil {
  814. logger.Warningf("Warning: failed to close temp file: %v", cerr)
  815. }
  816. }
  817. if _, err := os.Stat(tempPath); err == nil {
  818. if rerr := os.Remove(tempPath); rerr != nil {
  819. logger.Warningf("Warning: failed to remove temp file: %v", rerr)
  820. }
  821. }
  822. }()
  823. // Save uploaded file to temporary file
  824. if _, err = io.Copy(tempFile, file); err != nil {
  825. return common.NewErrorf("Error saving db: %v", err)
  826. }
  827. // Check if we can init the db or not
  828. if err = database.InitDB(tempPath); err != nil {
  829. return common.NewErrorf("Error checking db: %v", err)
  830. }
  831. // Stop Xray
  832. s.StopXrayService()
  833. // Backup the current database for fallback
  834. fallbackPath := fmt.Sprintf("%s.backup", config.GetDBPath())
  835. // Remove the existing fallback file (if any)
  836. if _, err := os.Stat(fallbackPath); err == nil {
  837. if errRemove := os.Remove(fallbackPath); errRemove != nil {
  838. return common.NewErrorf("Error removing existing fallback db file: %v", errRemove)
  839. }
  840. }
  841. // Move the current database to the fallback location
  842. if err = os.Rename(config.GetDBPath(), fallbackPath); err != nil {
  843. return common.NewErrorf("Error backing up current db file: %v", err)
  844. }
  845. // Defer fallback cleanup ONLY if everything goes well
  846. defer func() {
  847. if _, err := os.Stat(fallbackPath); err == nil {
  848. if rerr := os.Remove(fallbackPath); rerr != nil {
  849. logger.Warningf("Warning: failed to remove fallback file: %v", rerr)
  850. }
  851. }
  852. }()
  853. // Move temp to DB path
  854. if err = os.Rename(tempPath, config.GetDBPath()); err != nil {
  855. // Restore from fallback
  856. if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
  857. return common.NewErrorf("Error moving db file and restoring fallback: %v", errRename)
  858. }
  859. return common.NewErrorf("Error moving db file: %v", err)
  860. }
  861. // Migrate DB
  862. if err = database.InitDB(config.GetDBPath()); err != nil {
  863. if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
  864. return common.NewErrorf("Error migrating db and restoring fallback: %v", errRename)
  865. }
  866. return common.NewErrorf("Error migrating db: %v", err)
  867. }
  868. s.inboundService.MigrateDB()
  869. // Start Xray
  870. if err = s.RestartXrayService(); err != nil {
  871. return common.NewErrorf("Imported DB but failed to start Xray: %v", err)
  872. }
  873. return nil
  874. }
  875. func (s *ServerService) UpdateGeofile(fileName string) error {
  876. files := []struct {
  877. URL string
  878. FileName string
  879. }{
  880. {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip.dat"},
  881. {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite.dat"},
  882. {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geoip.dat", "geoip_IR.dat"},
  883. {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat", "geosite_IR.dat"},
  884. {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip_RU.dat"},
  885. {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite_RU.dat"},
  886. }
  887. downloadFile := func(url, destPath string) error {
  888. resp, err := http.Get(url)
  889. if err != nil {
  890. return common.NewErrorf("Failed to download Geofile from %s: %v", url, err)
  891. }
  892. defer resp.Body.Close()
  893. file, err := os.Create(destPath)
  894. if err != nil {
  895. return common.NewErrorf("Failed to create Geofile %s: %v", destPath, err)
  896. }
  897. defer file.Close()
  898. _, err = io.Copy(file, resp.Body)
  899. if err != nil {
  900. return common.NewErrorf("Failed to save Geofile %s: %v", destPath, err)
  901. }
  902. return nil
  903. }
  904. var errorMessages []string
  905. if fileName == "" {
  906. for _, file := range files {
  907. destPath := fmt.Sprintf("%s/%s", config.GetBinFolderPath(), file.FileName)
  908. if err := downloadFile(file.URL, destPath); err != nil {
  909. errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", file.FileName, err))
  910. }
  911. }
  912. } else {
  913. destPath := fmt.Sprintf("%s/%s", config.GetBinFolderPath(), fileName)
  914. var fileURL string
  915. for _, file := range files {
  916. if file.FileName == fileName {
  917. fileURL = file.URL
  918. break
  919. }
  920. }
  921. if fileURL == "" {
  922. errorMessages = append(errorMessages, fmt.Sprintf("File '%s' not found in the list of Geofiles", fileName))
  923. }
  924. if err := downloadFile(fileURL, destPath); err != nil {
  925. errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", fileName, err))
  926. }
  927. }
  928. err := s.RestartXrayService()
  929. if err != nil {
  930. errorMessages = append(errorMessages, fmt.Sprintf("Updated Geofile '%s' but Failed to start Xray: %v", fileName, err))
  931. }
  932. if len(errorMessages) > 0 {
  933. return common.NewErrorf("%s", strings.Join(errorMessages, "\r\n"))
  934. }
  935. return nil
  936. }
  937. func (s *ServerService) GetNewX25519Cert() (any, error) {
  938. // Run the command
  939. cmd := exec.Command(xray.GetBinaryPath(), "x25519")
  940. var out bytes.Buffer
  941. cmd.Stdout = &out
  942. err := cmd.Run()
  943. if err != nil {
  944. return nil, err
  945. }
  946. lines := strings.Split(out.String(), "\n")
  947. privateKeyLine := strings.Split(lines[0], ":")
  948. publicKeyLine := strings.Split(lines[1], ":")
  949. privateKey := strings.TrimSpace(privateKeyLine[1])
  950. publicKey := strings.TrimSpace(publicKeyLine[1])
  951. keyPair := map[string]any{
  952. "privateKey": privateKey,
  953. "publicKey": publicKey,
  954. }
  955. return keyPair, nil
  956. }
  957. func (s *ServerService) GetNewmldsa65() (any, error) {
  958. // Run the command
  959. cmd := exec.Command(xray.GetBinaryPath(), "mldsa65")
  960. var out bytes.Buffer
  961. cmd.Stdout = &out
  962. err := cmd.Run()
  963. if err != nil {
  964. return nil, err
  965. }
  966. lines := strings.Split(out.String(), "\n")
  967. SeedLine := strings.Split(lines[0], ":")
  968. VerifyLine := strings.Split(lines[1], ":")
  969. seed := strings.TrimSpace(SeedLine[1])
  970. verify := strings.TrimSpace(VerifyLine[1])
  971. keyPair := map[string]any{
  972. "seed": seed,
  973. "verify": verify,
  974. }
  975. return keyPair, nil
  976. }
  977. func (s *ServerService) GetNewEchCert(sni string) (interface{}, error) {
  978. // Run the command
  979. cmd := exec.Command(xray.GetBinaryPath(), "tls", "ech", "--serverName", sni)
  980. var out bytes.Buffer
  981. cmd.Stdout = &out
  982. err := cmd.Run()
  983. if err != nil {
  984. return nil, err
  985. }
  986. lines := strings.Split(out.String(), "\n")
  987. if len(lines) < 4 {
  988. return nil, common.NewError("invalid ech cert")
  989. }
  990. configList := lines[1]
  991. serverKeys := lines[3]
  992. return map[string]interface{}{
  993. "echServerKeys": serverKeys,
  994. "echConfigList": configList,
  995. }, nil
  996. }
  997. func (s *ServerService) GetNewVlessEnc() (any, error) {
  998. cmd := exec.Command(xray.GetBinaryPath(), "vlessenc")
  999. var out bytes.Buffer
  1000. cmd.Stdout = &out
  1001. if err := cmd.Run(); err != nil {
  1002. return nil, err
  1003. }
  1004. lines := strings.Split(out.String(), "\n")
  1005. var auths []map[string]string
  1006. var current map[string]string
  1007. for _, line := range lines {
  1008. line = strings.TrimSpace(line)
  1009. if strings.HasPrefix(line, "Authentication:") {
  1010. if current != nil {
  1011. auths = append(auths, current)
  1012. }
  1013. current = map[string]string{
  1014. "label": strings.TrimSpace(strings.TrimPrefix(line, "Authentication:")),
  1015. }
  1016. } else if strings.HasPrefix(line, `"decryption"`) || strings.HasPrefix(line, `"encryption"`) {
  1017. parts := strings.SplitN(line, ":", 2)
  1018. if len(parts) == 2 && current != nil {
  1019. key := strings.Trim(parts[0], `" `)
  1020. val := strings.Trim(parts[1], `" `)
  1021. current[key] = val
  1022. }
  1023. }
  1024. }
  1025. if current != nil {
  1026. auths = append(auths, current)
  1027. }
  1028. return map[string]any{
  1029. "auths": auths,
  1030. }, nil
  1031. }
  1032. func (s *ServerService) GetNewUUID() (map[string]string, error) {
  1033. newUUID, err := uuid.NewRandom()
  1034. if err != nil {
  1035. return nil, fmt.Errorf("failed to generate UUID: %w", err)
  1036. }
  1037. return map[string]string{
  1038. "uuid": newUUID.String(),
  1039. }, nil
  1040. }
  1041. func (s *ServerService) GetNewmlkem768() (any, error) {
  1042. // Run the command
  1043. cmd := exec.Command(xray.GetBinaryPath(), "mlkem768")
  1044. var out bytes.Buffer
  1045. cmd.Stdout = &out
  1046. err := cmd.Run()
  1047. if err != nil {
  1048. return nil, err
  1049. }
  1050. lines := strings.Split(out.String(), "\n")
  1051. SeedLine := strings.Split(lines[0], ":")
  1052. ClientLine := strings.Split(lines[1], ":")
  1053. seed := strings.TrimSpace(SeedLine[1])
  1054. client := strings.TrimSpace(ClientLine[1])
  1055. keyPair := map[string]any{
  1056. "seed": seed,
  1057. "client": client,
  1058. }
  1059. return keyPair, nil
  1060. }