server.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  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. if tagVersion == "26.5.3" {
  502. continue
  503. }
  504. tagParts := strings.Split(tagVersion, ".")
  505. if len(tagParts) != 3 {
  506. continue
  507. }
  508. major, err1 := strconv.Atoi(tagParts[0])
  509. minor, err2 := strconv.Atoi(tagParts[1])
  510. patch, err3 := strconv.Atoi(tagParts[2])
  511. if err1 != nil || err2 != nil || err3 != nil {
  512. continue
  513. }
  514. if major > 26 || (major == 26 && minor > 4) || (major == 26 && minor == 4 && patch >= 25) {
  515. versions = append(versions, release.TagName)
  516. }
  517. }
  518. return versions, nil
  519. }
  520. func (s *ServerService) StopXrayService() error {
  521. err := s.xrayService.StopXray()
  522. if err != nil {
  523. logger.Error("stop xray failed:", err)
  524. return err
  525. }
  526. return nil
  527. }
  528. func (s *ServerService) RestartXrayService() error {
  529. err := s.xrayService.RestartXray(true)
  530. if err != nil {
  531. logger.Error("start xray failed:", err)
  532. return err
  533. }
  534. return nil
  535. }
  536. func (s *ServerService) downloadXRay(version string) (string, error) {
  537. osName := runtime.GOOS
  538. arch := runtime.GOARCH
  539. switch osName {
  540. case "darwin":
  541. osName = "macos"
  542. case "windows":
  543. osName = "windows"
  544. }
  545. switch arch {
  546. case "amd64":
  547. arch = "64"
  548. case "arm64":
  549. arch = "arm64-v8a"
  550. case "armv7":
  551. arch = "arm32-v7a"
  552. case "armv6":
  553. arch = "arm32-v6"
  554. case "armv5":
  555. arch = "arm32-v5"
  556. case "386":
  557. arch = "32"
  558. case "s390x":
  559. arch = "s390x"
  560. }
  561. fileName := fmt.Sprintf("Xray-%s-%s.zip", osName, arch)
  562. url := fmt.Sprintf("https://github.com/XTLS/Xray-core/releases/download/%s/%s", version, fileName)
  563. resp, err := http.Get(url)
  564. if err != nil {
  565. return "", err
  566. }
  567. defer resp.Body.Close()
  568. os.Remove(fileName)
  569. file, err := os.Create(fileName)
  570. if err != nil {
  571. return "", err
  572. }
  573. defer file.Close()
  574. _, err = io.Copy(file, resp.Body)
  575. if err != nil {
  576. return "", err
  577. }
  578. return fileName, nil
  579. }
  580. func (s *ServerService) UpdateXray(version string) error {
  581. // 1. Stop xray before doing anything
  582. if err := s.StopXrayService(); err != nil {
  583. logger.Warning("failed to stop xray before update:", err)
  584. }
  585. // 2. Download the zip
  586. zipFileName, err := s.downloadXRay(version)
  587. if err != nil {
  588. return err
  589. }
  590. defer os.Remove(zipFileName)
  591. zipFile, err := os.Open(zipFileName)
  592. if err != nil {
  593. return err
  594. }
  595. defer zipFile.Close()
  596. stat, err := zipFile.Stat()
  597. if err != nil {
  598. return err
  599. }
  600. reader, err := zip.NewReader(zipFile, stat.Size())
  601. if err != nil {
  602. return err
  603. }
  604. // 3. Helper to extract files
  605. copyZipFile := func(zipName string, fileName string) error {
  606. zipFile, err := reader.Open(zipName)
  607. if err != nil {
  608. return err
  609. }
  610. defer zipFile.Close()
  611. os.MkdirAll(filepath.Dir(fileName), 0755)
  612. os.Remove(fileName)
  613. file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, fs.ModePerm)
  614. if err != nil {
  615. return err
  616. }
  617. defer file.Close()
  618. _, err = io.Copy(file, zipFile)
  619. return err
  620. }
  621. // 4. Extract correct binary
  622. if runtime.GOOS == "windows" {
  623. targetBinary := filepath.Join("bin", "xray-windows-amd64.exe")
  624. err = copyZipFile("xray.exe", targetBinary)
  625. } else {
  626. err = copyZipFile("xray", xray.GetBinaryPath())
  627. }
  628. if err != nil {
  629. return err
  630. }
  631. // 5. Restart xray
  632. if err := s.xrayService.RestartXray(true); err != nil {
  633. logger.Error("start xray failed:", err)
  634. return err
  635. }
  636. return nil
  637. }
  638. func (s *ServerService) GetLogs(count string, level string, syslog string) []string {
  639. c, _ := strconv.Atoi(count)
  640. var lines []string
  641. if syslog == "true" {
  642. // Check if running on Windows - journalctl is not available
  643. if runtime.GOOS == "windows" {
  644. return []string{"Syslog is not supported on Windows. Please use application logs instead by unchecking the 'Syslog' option."}
  645. }
  646. // Validate and sanitize count parameter
  647. countInt, err := strconv.Atoi(count)
  648. if err != nil || countInt < 1 || countInt > 10000 {
  649. return []string{"Invalid count parameter - must be a number between 1 and 10000"}
  650. }
  651. // Validate level parameter - only allow valid syslog levels
  652. validLevels := map[string]bool{
  653. "0": true, "emerg": true,
  654. "1": true, "alert": true,
  655. "2": true, "crit": true,
  656. "3": true, "err": true,
  657. "4": true, "warning": true,
  658. "5": true, "notice": true,
  659. "6": true, "info": true,
  660. "7": true, "debug": true,
  661. }
  662. if !validLevels[level] {
  663. return []string{"Invalid level parameter - must be a valid syslog level"}
  664. }
  665. // Use hardcoded command with validated parameters
  666. cmd := exec.Command("journalctl", "-u", "x-ui", "--no-pager", "-n", strconv.Itoa(countInt), "-p", level)
  667. var out bytes.Buffer
  668. cmd.Stdout = &out
  669. err = cmd.Run()
  670. if err != nil {
  671. return []string{"Failed to run journalctl command! Make sure systemd is available and x-ui service is registered."}
  672. }
  673. lines = strings.Split(out.String(), "\n")
  674. } else {
  675. lines = logger.GetLogs(c, level)
  676. }
  677. return lines
  678. }
  679. func (s *ServerService) GetXrayLogs(
  680. count string,
  681. filter string,
  682. showDirect string,
  683. showBlocked string,
  684. showProxy string,
  685. freedoms []string,
  686. blackholes []string) []LogEntry {
  687. const (
  688. Direct = iota
  689. Blocked
  690. Proxied
  691. )
  692. countInt, _ := strconv.Atoi(count)
  693. var entries []LogEntry
  694. pathToAccessLog, err := xray.GetAccessLogPath()
  695. if err != nil {
  696. return nil
  697. }
  698. file, err := os.Open(pathToAccessLog)
  699. if err != nil {
  700. return nil
  701. }
  702. defer file.Close()
  703. scanner := bufio.NewScanner(file)
  704. for scanner.Scan() {
  705. line := strings.TrimSpace(scanner.Text())
  706. if line == "" || strings.Contains(line, "api -> api") {
  707. //skipping empty lines and api calls
  708. continue
  709. }
  710. if filter != "" && !strings.Contains(line, filter) {
  711. //applying filter if it's not empty
  712. continue
  713. }
  714. var entry LogEntry
  715. parts := strings.Fields(line)
  716. for i, part := range parts {
  717. if i == 0 {
  718. dateTime, err := time.ParseInLocation("2006/01/02 15:04:05.999999", parts[0]+" "+parts[1], time.Local)
  719. if err != nil {
  720. continue
  721. }
  722. entry.DateTime = dateTime.UTC()
  723. }
  724. if part == "from" {
  725. entry.FromAddress = strings.TrimLeft(parts[i+1], "/")
  726. } else if part == "accepted" {
  727. entry.ToAddress = strings.TrimLeft(parts[i+1], "/")
  728. } else if strings.HasPrefix(part, "[") {
  729. entry.Inbound = part[1:]
  730. } else if strings.HasSuffix(part, "]") {
  731. entry.Outbound = part[:len(part)-1]
  732. } else if part == "email:" {
  733. entry.Email = parts[i+1]
  734. }
  735. }
  736. if logEntryContains(line, freedoms) {
  737. if showDirect == "false" {
  738. continue
  739. }
  740. entry.Event = Direct
  741. } else if logEntryContains(line, blackholes) {
  742. if showBlocked == "false" {
  743. continue
  744. }
  745. entry.Event = Blocked
  746. } else {
  747. if showProxy == "false" {
  748. continue
  749. }
  750. entry.Event = Proxied
  751. }
  752. entries = append(entries, entry)
  753. }
  754. if err := scanner.Err(); err != nil {
  755. return nil
  756. }
  757. if len(entries) > countInt {
  758. entries = entries[len(entries)-countInt:]
  759. }
  760. return entries
  761. }
  762. func logEntryContains(line string, suffixes []string) bool {
  763. for _, sfx := range suffixes {
  764. if strings.Contains(line, sfx+"]") {
  765. return true
  766. }
  767. }
  768. return false
  769. }
  770. func (s *ServerService) GetConfigJson() (any, error) {
  771. config, err := s.xrayService.GetXrayConfig()
  772. if err != nil {
  773. return nil, err
  774. }
  775. contents, err := json.MarshalIndent(config, "", " ")
  776. if err != nil {
  777. return nil, err
  778. }
  779. var jsonData any
  780. err = json.Unmarshal(contents, &jsonData)
  781. if err != nil {
  782. return nil, err
  783. }
  784. return jsonData, nil
  785. }
  786. func (s *ServerService) GetDb() ([]byte, error) {
  787. // Update by manually trigger a checkpoint operation
  788. err := database.Checkpoint()
  789. if err != nil {
  790. return nil, err
  791. }
  792. // Open the file for reading
  793. file, err := os.Open(config.GetDBPath())
  794. if err != nil {
  795. return nil, err
  796. }
  797. defer file.Close()
  798. // Read the file contents
  799. fileContents, err := io.ReadAll(file)
  800. if err != nil {
  801. return nil, err
  802. }
  803. return fileContents, nil
  804. }
  805. func (s *ServerService) ImportDB(file multipart.File) error {
  806. // Check if the file is a SQLite database
  807. isValidDb, err := database.IsSQLiteDB(file)
  808. if err != nil {
  809. return common.NewErrorf("Error checking db file format: %v", err)
  810. }
  811. if !isValidDb {
  812. return common.NewError("Invalid db file format")
  813. }
  814. // Reset the file reader to the beginning
  815. _, err = file.Seek(0, 0)
  816. if err != nil {
  817. return common.NewErrorf("Error resetting file reader: %v", err)
  818. }
  819. // Save the file as a temporary file
  820. tempPath := fmt.Sprintf("%s.temp", config.GetDBPath())
  821. // Remove the existing temporary file (if any)
  822. if _, err := os.Stat(tempPath); err == nil {
  823. if errRemove := os.Remove(tempPath); errRemove != nil {
  824. return common.NewErrorf("Error removing existing temporary db file: %v", errRemove)
  825. }
  826. }
  827. // Create the temporary file
  828. tempFile, err := os.Create(tempPath)
  829. if err != nil {
  830. return common.NewErrorf("Error creating temporary db file: %v", err)
  831. }
  832. // Robust deferred cleanup for the temporary file
  833. defer func() {
  834. if tempFile != nil {
  835. if cerr := tempFile.Close(); cerr != nil {
  836. logger.Warningf("Warning: failed to close temp file: %v", cerr)
  837. }
  838. }
  839. if _, err := os.Stat(tempPath); err == nil {
  840. if rerr := os.Remove(tempPath); rerr != nil {
  841. logger.Warningf("Warning: failed to remove temp file: %v", rerr)
  842. }
  843. }
  844. }()
  845. // Save uploaded file to temporary file
  846. if _, err = io.Copy(tempFile, file); err != nil {
  847. return common.NewErrorf("Error saving db: %v", err)
  848. }
  849. // Close temp file before opening via sqlite
  850. if err = tempFile.Close(); err != nil {
  851. return common.NewErrorf("Error closing temporary db file: %v", err)
  852. }
  853. tempFile = nil
  854. // Validate integrity (no migrations / side effects)
  855. if err = database.ValidateSQLiteDB(tempPath); err != nil {
  856. return common.NewErrorf("Invalid or corrupt db file: %v", err)
  857. }
  858. // Stop Xray (ignore error but log)
  859. if errStop := s.StopXrayService(); errStop != nil {
  860. logger.Warningf("Failed to stop Xray before DB import: %v", errStop)
  861. }
  862. // Close existing DB to release file locks (especially on Windows)
  863. if errClose := database.CloseDB(); errClose != nil {
  864. logger.Warningf("Failed to close existing DB before replacement: %v", errClose)
  865. }
  866. // Backup the current database for fallback
  867. fallbackPath := fmt.Sprintf("%s.backup", config.GetDBPath())
  868. // Remove the existing fallback file (if any)
  869. if _, err := os.Stat(fallbackPath); err == nil {
  870. if errRemove := os.Remove(fallbackPath); errRemove != nil {
  871. return common.NewErrorf("Error removing existing fallback db file: %v", errRemove)
  872. }
  873. }
  874. // Move the current database to the fallback location
  875. if err = os.Rename(config.GetDBPath(), fallbackPath); err != nil {
  876. return common.NewErrorf("Error backing up current db file: %v", err)
  877. }
  878. // Defer fallback cleanup ONLY if everything goes well
  879. defer func() {
  880. if _, err := os.Stat(fallbackPath); err == nil {
  881. if rerr := os.Remove(fallbackPath); rerr != nil {
  882. logger.Warningf("Warning: failed to remove fallback file: %v", rerr)
  883. }
  884. }
  885. }()
  886. // Move temp to DB path
  887. if err = os.Rename(tempPath, config.GetDBPath()); err != nil {
  888. // Restore from fallback
  889. if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
  890. return common.NewErrorf("Error moving db file and restoring fallback: %v", errRename)
  891. }
  892. return common.NewErrorf("Error moving db file: %v", err)
  893. }
  894. // Open & migrate new DB
  895. if err = database.InitDB(config.GetDBPath()); err != nil {
  896. if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
  897. return common.NewErrorf("Error migrating db and restoring fallback: %v", errRename)
  898. }
  899. return common.NewErrorf("Error migrating db: %v", err)
  900. }
  901. s.inboundService.MigrateDB()
  902. // Start Xray
  903. if err = s.RestartXrayService(); err != nil {
  904. return common.NewErrorf("Imported DB but failed to start Xray: %v", err)
  905. }
  906. return nil
  907. }
  908. // IsValidGeofileName validates that the filename is safe for geofile operations.
  909. // It checks for path traversal attempts and ensures the filename contains only safe characters.
  910. func (s *ServerService) IsValidGeofileName(filename string) bool {
  911. if filename == "" {
  912. return false
  913. }
  914. // Check for path traversal attempts
  915. if strings.Contains(filename, "..") {
  916. return false
  917. }
  918. // Check for path separators (both forward and backward slash)
  919. if strings.ContainsAny(filename, `/\`) {
  920. return false
  921. }
  922. // Check for absolute path indicators
  923. if filepath.IsAbs(filename) {
  924. return false
  925. }
  926. // Additional security: only allow alphanumeric, dots, underscores, and hyphens
  927. // This is stricter than the general filename regex
  928. validGeofilePattern := `^[a-zA-Z0-9._-]+\.dat$`
  929. matched, _ := regexp.MatchString(validGeofilePattern, filename)
  930. return matched
  931. }
  932. func (s *ServerService) UpdateGeofile(fileName string) error {
  933. type geofileEntry struct {
  934. URL string
  935. FileName string
  936. }
  937. geofileAllowlist := map[string]geofileEntry{
  938. "geoip.dat": {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip.dat"},
  939. "geosite.dat": {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite.dat"},
  940. "geoip_IR.dat": {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geoip.dat", "geoip_IR.dat"},
  941. "geosite_IR.dat": {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat", "geosite_IR.dat"},
  942. "geoip_RU.dat": {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip_RU.dat"},
  943. "geosite_RU.dat": {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite_RU.dat"},
  944. }
  945. // Strict allowlist check to avoid writing uncontrolled files
  946. if fileName != "" {
  947. if _, ok := geofileAllowlist[fileName]; !ok {
  948. return common.NewErrorf("Invalid geofile name: %q not in allowlist", fileName)
  949. }
  950. }
  951. downloadFile := func(url, destPath string) error {
  952. var req *http.Request
  953. req, err := http.NewRequest("GET", url, nil)
  954. if err != nil {
  955. return common.NewErrorf("Failed to create HTTP request for %s: %v", url, err)
  956. }
  957. var localFileModTime time.Time
  958. if fileInfo, err := os.Stat(destPath); err == nil {
  959. localFileModTime = fileInfo.ModTime()
  960. if !localFileModTime.IsZero() {
  961. req.Header.Set("If-Modified-Since", localFileModTime.UTC().Format(http.TimeFormat))
  962. }
  963. }
  964. client := &http.Client{}
  965. resp, err := client.Do(req)
  966. if err != nil {
  967. return common.NewErrorf("Failed to download Geofile from %s: %v", url, err)
  968. }
  969. defer resp.Body.Close()
  970. // Parse Last-Modified header from server
  971. var serverModTime time.Time
  972. serverModTimeStr := resp.Header.Get("Last-Modified")
  973. if serverModTimeStr != "" {
  974. parsedTime, err := time.Parse(http.TimeFormat, serverModTimeStr)
  975. if err != nil {
  976. logger.Warningf("Failed to parse Last-Modified header for %s: %v", url, err)
  977. } else {
  978. serverModTime = parsedTime
  979. }
  980. }
  981. // Function to update local file's modification time
  982. updateFileModTime := func() {
  983. if !serverModTime.IsZero() {
  984. if err := os.Chtimes(destPath, serverModTime, serverModTime); err != nil {
  985. logger.Warningf("Failed to update modification time for %s: %v", destPath, err)
  986. }
  987. }
  988. }
  989. // Handle 304 Not Modified
  990. if resp.StatusCode == http.StatusNotModified {
  991. updateFileModTime()
  992. return nil
  993. }
  994. if resp.StatusCode != http.StatusOK {
  995. return common.NewErrorf("Failed to download Geofile from %s: received status code %d", url, resp.StatusCode)
  996. }
  997. file, err := os.Create(destPath)
  998. if err != nil {
  999. return common.NewErrorf("Failed to create Geofile %s: %v", destPath, err)
  1000. }
  1001. defer file.Close()
  1002. _, err = io.Copy(file, resp.Body)
  1003. if err != nil {
  1004. return common.NewErrorf("Failed to save Geofile %s: %v", destPath, err)
  1005. }
  1006. updateFileModTime()
  1007. return nil
  1008. }
  1009. var errorMessages []string
  1010. if fileName == "" {
  1011. // Download all geofiles
  1012. for _, entry := range geofileAllowlist {
  1013. destPath := filepath.Join(config.GetBinFolderPath(), entry.FileName)
  1014. if err := downloadFile(entry.URL, destPath); err != nil {
  1015. errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", entry.FileName, err))
  1016. }
  1017. }
  1018. } else {
  1019. entry := geofileAllowlist[fileName]
  1020. destPath := filepath.Join(config.GetBinFolderPath(), entry.FileName)
  1021. if err := downloadFile(entry.URL, destPath); err != nil {
  1022. errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", entry.FileName, err))
  1023. }
  1024. }
  1025. err := s.RestartXrayService()
  1026. if err != nil {
  1027. errorMessages = append(errorMessages, fmt.Sprintf("Updated Geofile '%s' but Failed to start Xray: %v", fileName, err))
  1028. }
  1029. if len(errorMessages) > 0 {
  1030. return common.NewErrorf("%s", strings.Join(errorMessages, "\r\n"))
  1031. }
  1032. return nil
  1033. }
  1034. func (s *ServerService) GetNewX25519Cert() (any, error) {
  1035. // Run the command
  1036. cmd := exec.Command(xray.GetBinaryPath(), "x25519")
  1037. var out bytes.Buffer
  1038. cmd.Stdout = &out
  1039. err := cmd.Run()
  1040. if err != nil {
  1041. return nil, err
  1042. }
  1043. lines := strings.Split(out.String(), "\n")
  1044. privateKeyLine := strings.Split(lines[0], ":")
  1045. publicKeyLine := strings.Split(lines[1], ":")
  1046. privateKey := strings.TrimSpace(privateKeyLine[1])
  1047. publicKey := strings.TrimSpace(publicKeyLine[1])
  1048. keyPair := map[string]any{
  1049. "privateKey": privateKey,
  1050. "publicKey": publicKey,
  1051. }
  1052. return keyPair, nil
  1053. }
  1054. func (s *ServerService) GetNewmldsa65() (any, error) {
  1055. // Run the command
  1056. cmd := exec.Command(xray.GetBinaryPath(), "mldsa65")
  1057. var out bytes.Buffer
  1058. cmd.Stdout = &out
  1059. err := cmd.Run()
  1060. if err != nil {
  1061. return nil, err
  1062. }
  1063. lines := strings.Split(out.String(), "\n")
  1064. SeedLine := strings.Split(lines[0], ":")
  1065. VerifyLine := strings.Split(lines[1], ":")
  1066. seed := strings.TrimSpace(SeedLine[1])
  1067. verify := strings.TrimSpace(VerifyLine[1])
  1068. keyPair := map[string]any{
  1069. "seed": seed,
  1070. "verify": verify,
  1071. }
  1072. return keyPair, nil
  1073. }
  1074. func (s *ServerService) GetNewEchCert(sni string) (any, error) {
  1075. // Run the command
  1076. cmd := exec.Command(xray.GetBinaryPath(), "tls", "ech", "--serverName", sni)
  1077. var out bytes.Buffer
  1078. cmd.Stdout = &out
  1079. err := cmd.Run()
  1080. if err != nil {
  1081. return nil, err
  1082. }
  1083. lines := strings.Split(out.String(), "\n")
  1084. if len(lines) < 4 {
  1085. return nil, common.NewError("invalid ech cert")
  1086. }
  1087. configList := lines[1]
  1088. serverKeys := lines[3]
  1089. return map[string]any{
  1090. "echServerKeys": serverKeys,
  1091. "echConfigList": configList,
  1092. }, nil
  1093. }
  1094. func (s *ServerService) GetNewVlessEnc() (any, error) {
  1095. cmd := exec.Command(xray.GetBinaryPath(), "vlessenc")
  1096. var out bytes.Buffer
  1097. cmd.Stdout = &out
  1098. if err := cmd.Run(); err != nil {
  1099. return nil, err
  1100. }
  1101. lines := strings.Split(out.String(), "\n")
  1102. var auths []map[string]string
  1103. var current map[string]string
  1104. for _, line := range lines {
  1105. line = strings.TrimSpace(line)
  1106. if strings.HasPrefix(line, "Authentication:") {
  1107. if current != nil {
  1108. auths = append(auths, current)
  1109. }
  1110. current = map[string]string{
  1111. "label": strings.TrimSpace(strings.TrimPrefix(line, "Authentication:")),
  1112. }
  1113. } else if strings.HasPrefix(line, `"decryption"`) || strings.HasPrefix(line, `"encryption"`) {
  1114. parts := strings.SplitN(line, ":", 2)
  1115. if len(parts) == 2 && current != nil {
  1116. key := strings.Trim(parts[0], `" `)
  1117. val := strings.Trim(parts[1], `" `)
  1118. current[key] = val
  1119. }
  1120. }
  1121. }
  1122. if current != nil {
  1123. auths = append(auths, current)
  1124. }
  1125. return map[string]any{
  1126. "auths": auths,
  1127. }, nil
  1128. }
  1129. func (s *ServerService) GetNewUUID() (map[string]string, error) {
  1130. newUUID, err := uuid.NewRandom()
  1131. if err != nil {
  1132. return nil, fmt.Errorf("failed to generate UUID: %w", err)
  1133. }
  1134. return map[string]string{
  1135. "uuid": newUUID.String(),
  1136. }, nil
  1137. }
  1138. func (s *ServerService) GetNewmlkem768() (any, error) {
  1139. // Run the command
  1140. cmd := exec.Command(xray.GetBinaryPath(), "mlkem768")
  1141. var out bytes.Buffer
  1142. cmd.Stdout = &out
  1143. err := cmd.Run()
  1144. if err != nil {
  1145. return nil, err
  1146. }
  1147. lines := strings.Split(out.String(), "\n")
  1148. SeedLine := strings.Split(lines[0], ":")
  1149. ClientLine := strings.Split(lines[1], ":")
  1150. seed := strings.TrimSpace(SeedLine[1])
  1151. client := strings.TrimSpace(ClientLine[1])
  1152. keyPair := map[string]any{
  1153. "seed": seed,
  1154. "client": client,
  1155. }
  1156. return keyPair, nil
  1157. }