server.go 32 KB

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