server.go 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134
  1. package service
  2. import (
  3. "archive/zip"
  4. "bufio"
  5. "bytes"
  6. "crypto/sha256"
  7. "crypto/x509"
  8. "encoding/hex"
  9. "encoding/json"
  10. "encoding/pem"
  11. "fmt"
  12. "io"
  13. "mime/multipart"
  14. stdnet "net"
  15. "net/http"
  16. "net/url"
  17. "os"
  18. "os/exec"
  19. "path/filepath"
  20. "regexp"
  21. "runtime"
  22. "slices"
  23. "strconv"
  24. "strings"
  25. "sync"
  26. "time"
  27. "github.com/mhsanaei/3x-ui/v3/internal/config"
  28. "github.com/mhsanaei/3x-ui/v3/internal/database"
  29. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  30. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  31. "github.com/mhsanaei/3x-ui/v3/internal/util/sys"
  32. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  33. "github.com/google/uuid"
  34. utls "github.com/refraction-networking/utls"
  35. "github.com/shirou/gopsutil/v4/cpu"
  36. "github.com/shirou/gopsutil/v4/disk"
  37. "github.com/shirou/gopsutil/v4/host"
  38. "github.com/shirou/gopsutil/v4/load"
  39. "github.com/shirou/gopsutil/v4/mem"
  40. "github.com/shirou/gopsutil/v4/net"
  41. )
  42. // ProcessState represents the current state of a system process.
  43. type ProcessState string
  44. // Process state constants
  45. const (
  46. Running ProcessState = "running" // Process is running normally
  47. Stop ProcessState = "stop" // Process is stopped
  48. Error ProcessState = "error" // Process is in error state
  49. )
  50. // Status represents comprehensive system and application status information.
  51. // It includes CPU, memory, disk, network statistics, and Xray process status.
  52. type Status struct {
  53. T time.Time `json:"-"`
  54. Cpu float64 `json:"cpu"`
  55. CpuCores int `json:"cpuCores"`
  56. LogicalPro int `json:"logicalPro"`
  57. CpuSpeedMhz float64 `json:"cpuSpeedMhz"`
  58. Mem struct {
  59. Current uint64 `json:"current"`
  60. Total uint64 `json:"total"`
  61. } `json:"mem"`
  62. Swap struct {
  63. Current uint64 `json:"current"`
  64. Total uint64 `json:"total"`
  65. } `json:"swap"`
  66. Disk struct {
  67. Current uint64 `json:"current"`
  68. Total uint64 `json:"total"`
  69. } `json:"disk"`
  70. DiskIO struct {
  71. Read uint64 `json:"read"`
  72. Write uint64 `json:"write"`
  73. } `json:"diskIO"`
  74. DiskTraffic struct {
  75. Read uint64 `json:"read"`
  76. Write uint64 `json:"write"`
  77. } `json:"diskTraffic"`
  78. Xray struct {
  79. State ProcessState `json:"state"`
  80. ErrorMsg string `json:"errorMsg"`
  81. Version string `json:"version"`
  82. } `json:"xray"`
  83. PanelVersion string `json:"panelVersion"`
  84. PanelGuid string `json:"panelGuid"`
  85. Uptime uint64 `json:"uptime"`
  86. Loads []float64 `json:"loads"`
  87. TcpCount int `json:"tcpCount"`
  88. UdpCount int `json:"udpCount"`
  89. NetIO struct {
  90. Up uint64 `json:"up"`
  91. Down uint64 `json:"down"`
  92. PktUp uint64 `json:"pktUp"`
  93. PktDown uint64 `json:"pktDown"`
  94. } `json:"netIO"`
  95. NetTraffic struct {
  96. Sent uint64 `json:"sent"`
  97. Recv uint64 `json:"recv"`
  98. PktSent uint64 `json:"pktSent"`
  99. PktRecv uint64 `json:"pktRecv"`
  100. } `json:"netTraffic"`
  101. PublicIP struct {
  102. IPv4 string `json:"ipv4"`
  103. IPv6 string `json:"ipv6"`
  104. } `json:"publicIP"`
  105. AppStats struct {
  106. Threads uint32 `json:"threads"`
  107. Mem uint64 `json:"mem"`
  108. Uptime uint64 `json:"uptime"`
  109. } `json:"appStats"`
  110. }
  111. // Release represents information about a software release from GitHub.
  112. type Release struct {
  113. TagName string `json:"tag_name"` // The tag name of the release
  114. }
  115. // ServerService provides business logic for server monitoring and management.
  116. // It handles system status collection, IP detection, and application statistics.
  117. type ServerService struct {
  118. xrayService XrayService
  119. inboundService InboundService
  120. settingService SettingService
  121. cachedIPv4 string
  122. cachedIPv6 string
  123. noIPv6 bool
  124. mu sync.Mutex
  125. lastCPUTimes cpu.TimesStat
  126. hasLastCPUSample bool
  127. hasNativeCPUSample bool
  128. emaCPU float64
  129. cachedCpuSpeedMhz float64
  130. lastCpuInfoAttempt time.Time
  131. lastStatusMu sync.RWMutex
  132. lastStatus *Status
  133. versionsCacheMu sync.Mutex
  134. versionsCache *cachedXrayVersions
  135. fail2banMu sync.Mutex
  136. fail2banInstalled bool
  137. fail2banCheckedAt time.Time
  138. }
  139. type cachedXrayVersions struct {
  140. versions []string
  141. fetchedAt time.Time
  142. }
  143. // xrayVersionsCacheTTL bounds how often /getXrayVersion hits GitHub. The list
  144. // is purely informational (rendered in the "switch Xray version" picker) so a
  145. // quarter-hour staleness window is fine and saves the API budget.
  146. const xrayVersionsCacheTTL = 15 * time.Minute
  147. // allowedHistoryBuckets is the bucket-second whitelist for time-series
  148. // aggregation endpoints (server + node metrics). Restricting it prevents
  149. // callers from triggering arbitrary aggregation work and keeps the
  150. // frontend's bucket selector self-documenting.
  151. var allowedHistoryBuckets = map[int]bool{
  152. 2: true, // Real-time view
  153. 30: true, // 30s intervals
  154. 60: true, // 1m intervals
  155. 120: true, // 2m intervals
  156. 180: true, // 3m intervals
  157. 300: true, // 5m intervals
  158. 720: true, // 12m intervals
  159. 1440: true, // 24m intervals
  160. 2880: true, // 48m intervals
  161. }
  162. // IsAllowedHistoryBucket reports whether a bucket-seconds value is in the
  163. // whitelist used by /server/history, /server/cpuHistory, /server/xrayMetricsHistory,
  164. // /server/xrayObservatoryHistory, and /nodes/history.
  165. func IsAllowedHistoryBucket(bucketSeconds int) bool {
  166. return allowedHistoryBuckets[bucketSeconds]
  167. }
  168. // LastStatus returns the most recent Status snapshot collected by
  169. // RefreshStatus. Safe for concurrent readers.
  170. func (s *ServerService) LastStatus() *Status {
  171. s.lastStatusMu.RLock()
  172. defer s.lastStatusMu.RUnlock()
  173. return s.lastStatus
  174. }
  175. // Fail2banStatus tells the frontend whether the per-client IP limit can
  176. // actually be enforced. Enforcement depends on fail2ban, so a limit set
  177. // without it would silently do nothing.
  178. type Fail2banStatus struct {
  179. Enabled bool `json:"enabled"`
  180. Installed bool `json:"installed"`
  181. Usable bool `json:"usable"`
  182. Windows bool `json:"windows"`
  183. }
  184. const fail2banInstalledCacheTTL = 30 * time.Second
  185. func (s *ServerService) GetFail2banStatus() Fail2banStatus {
  186. enabled := isFail2banEnabled()
  187. installed := false
  188. if enabled {
  189. installed = s.isFail2banInstalled()
  190. }
  191. return Fail2banStatus{
  192. Enabled: enabled,
  193. Installed: installed,
  194. Usable: enabled && installed,
  195. Windows: runtime.GOOS == "windows",
  196. }
  197. }
  198. func isFail2banEnabled() bool {
  199. value, ok := os.LookupEnv("XUI_ENABLE_FAIL2BAN")
  200. return !ok || value == "true"
  201. }
  202. func (s *ServerService) isFail2banInstalled() bool {
  203. s.fail2banMu.Lock()
  204. defer s.fail2banMu.Unlock()
  205. if !s.fail2banCheckedAt.IsZero() && time.Since(s.fail2banCheckedAt) < fail2banInstalledCacheTTL {
  206. return s.fail2banInstalled
  207. }
  208. err := exec.Command("fail2ban-client", "-h").Run()
  209. s.fail2banInstalled = err == nil
  210. s.fail2banCheckedAt = time.Now()
  211. return s.fail2banInstalled
  212. }
  213. // RefreshStatus collects a new system snapshot, stores it as LastStatus, and
  214. // appends it to the system-metrics time series. Returns the new snapshot (may
  215. // be nil if collection failed). Called by the background ticker; the caller is
  216. // responsible for any side effects (websocket broadcast, xray metrics sample).
  217. func (s *ServerService) RefreshStatus() *Status {
  218. next := s.GetStatus(s.LastStatus())
  219. if next == nil {
  220. return nil
  221. }
  222. s.lastStatusMu.Lock()
  223. s.lastStatus = next
  224. s.lastStatusMu.Unlock()
  225. s.AppendStatusSample(time.Now(), next)
  226. return next
  227. }
  228. // GetXrayVersionsCached wraps GetXrayVersions with a TTL cache. On fetch
  229. // failure we serve the last successful list (if any) so the UI doesn't go
  230. // blank during a GitHub API hiccup; if there's no cache at all the underlying
  231. // error is surfaced.
  232. func (s *ServerService) GetXrayVersionsCached() ([]string, error) {
  233. s.versionsCacheMu.Lock()
  234. cache := s.versionsCache
  235. s.versionsCacheMu.Unlock()
  236. if cache != nil && time.Since(cache.fetchedAt) <= xrayVersionsCacheTTL {
  237. return cache.versions, nil
  238. }
  239. versions, err := s.GetXrayVersions()
  240. if err != nil {
  241. if cache != nil {
  242. logger.Warning("GetXrayVersionsCached: serving stale list:", err)
  243. return cache.versions, nil
  244. }
  245. return nil, err
  246. }
  247. s.versionsCacheMu.Lock()
  248. s.versionsCache = &cachedXrayVersions{versions: versions, fetchedAt: time.Now()}
  249. s.versionsCacheMu.Unlock()
  250. return versions, nil
  251. }
  252. // GetDefaultLogOutboundTags scans the default Xray config for freedom and
  253. // blackhole outbound tags so /getXrayLogs can colour-code log lines without
  254. // the controller re-doing the JSON walk. Falls back to the historical
  255. // "direct"/"blocked" defaults when the config can't be read.
  256. func (s *ServerService) GetDefaultLogOutboundTags() (freedoms, blackholes []string) {
  257. config, err := s.settingService.GetDefaultXrayConfig()
  258. if err == nil && config != nil {
  259. if cfgMap, ok := config.(map[string]any); ok {
  260. if outbounds, ok := cfgMap["outbounds"].([]any); ok {
  261. for _, outbound := range outbounds {
  262. obMap, ok := outbound.(map[string]any)
  263. if !ok {
  264. continue
  265. }
  266. tag, _ := obMap["tag"].(string)
  267. if tag == "" {
  268. continue
  269. }
  270. switch obMap["protocol"] {
  271. case "freedom":
  272. freedoms = append(freedoms, tag)
  273. case "blackhole":
  274. blackholes = append(blackholes, tag)
  275. }
  276. }
  277. }
  278. }
  279. }
  280. if len(freedoms) == 0 {
  281. freedoms = []string{"direct"}
  282. }
  283. if len(blackholes) == 0 {
  284. blackholes = []string{"blocked"}
  285. }
  286. return freedoms, blackholes
  287. }
  288. // AggregateCpuHistory returns up to maxPoints averaged buckets of size bucketSeconds.
  289. // Kept for back-compat with the original /panel/api/server/cpuHistory/:bucket route;
  290. // the response key is "cpu" (not "v") so legacy consumers parse unchanged.
  291. func (s *ServerService) AggregateCpuHistory(bucketSeconds int, maxPoints int) []map[string]any {
  292. out := systemMetrics.aggregate("cpu", bucketSeconds, maxPoints)
  293. for _, p := range out {
  294. p["cpu"] = p["v"]
  295. delete(p, "v")
  296. }
  297. return out
  298. }
  299. // AggregateSystemMetric returns up to maxPoints averaged buckets for any
  300. // known system metric (see SystemMetricKeys). Output points have keys
  301. // {"t": unixSec, "v": value}; the caller decides how to format the value.
  302. func (s *ServerService) AggregateSystemMetric(metric string, bucketSeconds int, maxPoints int) []map[string]any {
  303. return systemMetrics.aggregate(metric, bucketSeconds, maxPoints)
  304. }
  305. type LogEntry struct {
  306. DateTime time.Time
  307. FromAddress string
  308. ToAddress string
  309. Inbound string
  310. Outbound string
  311. Email string
  312. Event int
  313. }
  314. func getPublicIP(url string) string {
  315. client := &http.Client{
  316. Timeout: 3 * time.Second,
  317. }
  318. resp, err := client.Get(url)
  319. if err != nil {
  320. return "N/A"
  321. }
  322. defer resp.Body.Close()
  323. // Don't retry if access is blocked or region-restricted
  324. if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusUnavailableForLegalReasons {
  325. return "N/A"
  326. }
  327. if resp.StatusCode != http.StatusOK {
  328. return "N/A"
  329. }
  330. ip, err := io.ReadAll(resp.Body)
  331. if err != nil {
  332. return "N/A"
  333. }
  334. ipString := strings.TrimSpace(string(ip))
  335. if ipString == "" {
  336. return "N/A"
  337. }
  338. return ipString
  339. }
  340. func (s *ServerService) GetStatus(lastStatus *Status) *Status {
  341. now := time.Now()
  342. status := &Status{
  343. T: now,
  344. }
  345. // CPU stats
  346. util, err := s.sampleCPUUtilization()
  347. if err != nil {
  348. logger.Warning("get cpu percent failed:", err)
  349. } else {
  350. status.Cpu = util
  351. }
  352. status.CpuCores, err = cpu.Counts(false)
  353. if err != nil {
  354. logger.Warning("get cpu cores count failed:", err)
  355. }
  356. status.LogicalPro = runtime.NumCPU()
  357. if status.CpuSpeedMhz = s.cachedCpuSpeedMhz; s.cachedCpuSpeedMhz == 0 && time.Since(s.lastCpuInfoAttempt) > 5*time.Minute {
  358. s.lastCpuInfoAttempt = time.Now()
  359. done := make(chan struct{})
  360. go func() {
  361. defer close(done)
  362. cpuInfos, err := cpu.Info()
  363. if err != nil {
  364. logger.Warning("get cpu info failed:", err)
  365. return
  366. }
  367. if len(cpuInfos) > 0 {
  368. s.cachedCpuSpeedMhz = cpuInfos[0].Mhz
  369. status.CpuSpeedMhz = s.cachedCpuSpeedMhz
  370. } else {
  371. logger.Warning("could not find cpu info")
  372. }
  373. }()
  374. select {
  375. case <-done:
  376. case <-time.After(1500 * time.Millisecond):
  377. logger.Warning("cpu info query timed out; will retry later")
  378. }
  379. } else if s.cachedCpuSpeedMhz != 0 {
  380. status.CpuSpeedMhz = s.cachedCpuSpeedMhz
  381. }
  382. // Uptime
  383. upTime, err := host.Uptime()
  384. if err != nil {
  385. logger.Warning("get uptime failed:", err)
  386. } else {
  387. status.Uptime = upTime
  388. }
  389. // Memory stats
  390. memInfo, err := mem.VirtualMemory()
  391. if err != nil {
  392. logger.Warning("get virtual memory failed:", err)
  393. } else {
  394. status.Mem.Current = memInfo.Used
  395. status.Mem.Total = memInfo.Total
  396. }
  397. swapInfo, err := mem.SwapMemory()
  398. if err != nil {
  399. logger.Warning("get swap memory failed:", err)
  400. } else {
  401. status.Swap.Current = swapInfo.Used
  402. status.Swap.Total = swapInfo.Total
  403. }
  404. // Disk stats
  405. diskInfo, err := disk.Usage("/")
  406. if err != nil {
  407. logger.Warning("get disk usage failed:", err)
  408. } else {
  409. status.Disk.Current = diskInfo.Used
  410. status.Disk.Total = diskInfo.Total
  411. }
  412. diskIOStats, err := disk.IOCounters()
  413. if err != nil {
  414. logger.Warning("get disk io counters failed:", err)
  415. } else {
  416. var totalRead, totalWrite uint64
  417. for _, counter := range diskIOStats {
  418. totalRead += counter.ReadBytes
  419. totalWrite += counter.WriteBytes
  420. }
  421. status.DiskTraffic.Read = totalRead
  422. status.DiskTraffic.Write = totalWrite
  423. if lastStatus != nil {
  424. duration := now.Sub(lastStatus.T)
  425. seconds := float64(duration) / float64(time.Second)
  426. if seconds > 0 && status.DiskTraffic.Read >= lastStatus.DiskTraffic.Read {
  427. status.DiskIO.Read = uint64(float64(status.DiskTraffic.Read-lastStatus.DiskTraffic.Read) / seconds)
  428. }
  429. if seconds > 0 && status.DiskTraffic.Write >= lastStatus.DiskTraffic.Write {
  430. status.DiskIO.Write = uint64(float64(status.DiskTraffic.Write-lastStatus.DiskTraffic.Write) / seconds)
  431. }
  432. }
  433. }
  434. // Load averages
  435. avgState, err := load.Avg()
  436. if err != nil {
  437. logger.Warning("get load avg failed:", err)
  438. } else {
  439. status.Loads = []float64{avgState.Load1, avgState.Load5, avgState.Load15}
  440. }
  441. // Network stats
  442. ioStats, err := net.IOCounters(true)
  443. if err != nil {
  444. logger.Warning("get io counters failed:", err)
  445. } else {
  446. var totalSent, totalRecv, totalPktSent, totalPktRecv uint64
  447. for _, iface := range ioStats {
  448. name := strings.ToLower(iface.Name)
  449. if isVirtualInterface(name) {
  450. continue
  451. }
  452. totalSent += iface.BytesSent
  453. totalRecv += iface.BytesRecv
  454. totalPktSent += iface.PacketsSent
  455. totalPktRecv += iface.PacketsRecv
  456. }
  457. status.NetTraffic.Sent = totalSent
  458. status.NetTraffic.Recv = totalRecv
  459. status.NetTraffic.PktSent = totalPktSent
  460. status.NetTraffic.PktRecv = totalPktRecv
  461. if lastStatus != nil {
  462. duration := now.Sub(lastStatus.T)
  463. seconds := float64(duration) / float64(time.Second)
  464. up := uint64(float64(status.NetTraffic.Sent-lastStatus.NetTraffic.Sent) / seconds)
  465. down := uint64(float64(status.NetTraffic.Recv-lastStatus.NetTraffic.Recv) / seconds)
  466. status.NetIO.Up = up
  467. status.NetIO.Down = down
  468. if seconds > 0 && status.NetTraffic.PktSent >= lastStatus.NetTraffic.PktSent {
  469. status.NetIO.PktUp = uint64(float64(status.NetTraffic.PktSent-lastStatus.NetTraffic.PktSent) / seconds)
  470. }
  471. if seconds > 0 && status.NetTraffic.PktRecv >= lastStatus.NetTraffic.PktRecv {
  472. status.NetIO.PktDown = uint64(float64(status.NetTraffic.PktRecv-lastStatus.NetTraffic.PktRecv) / seconds)
  473. }
  474. }
  475. }
  476. // TCP/UDP connections
  477. status.TcpCount, err = sys.GetTCPCount()
  478. if err != nil {
  479. logger.Warning("get tcp connections failed:", err)
  480. }
  481. status.UdpCount, err = sys.GetUDPCount()
  482. if err != nil {
  483. logger.Warning("get udp connections failed:", err)
  484. }
  485. // IP fetching with caching
  486. showIp4ServiceLists := []string{
  487. "https://api4.ipify.org",
  488. "https://ipv4.icanhazip.com",
  489. "https://v4.api.ipinfo.io/ip",
  490. "https://ipv4.myexternalip.com/raw",
  491. "https://4.ident.me",
  492. "https://check-host.net/ip",
  493. }
  494. showIp6ServiceLists := []string{
  495. "https://api6.ipify.org",
  496. "https://ipv6.icanhazip.com",
  497. "https://v6.api.ipinfo.io/ip",
  498. "https://ipv6.myexternalip.com/raw",
  499. "https://6.ident.me",
  500. }
  501. if s.cachedIPv4 == "" {
  502. for _, ip4Service := range showIp4ServiceLists {
  503. s.cachedIPv4 = getPublicIP(ip4Service)
  504. if s.cachedIPv4 != "N/A" {
  505. break
  506. }
  507. }
  508. }
  509. if s.cachedIPv6 == "" && !s.noIPv6 {
  510. for _, ip6Service := range showIp6ServiceLists {
  511. s.cachedIPv6 = getPublicIP(ip6Service)
  512. if s.cachedIPv6 != "N/A" {
  513. break
  514. }
  515. }
  516. }
  517. if s.cachedIPv6 == "N/A" {
  518. s.noIPv6 = true
  519. }
  520. status.PublicIP.IPv4 = s.cachedIPv4
  521. status.PublicIP.IPv6 = s.cachedIPv6
  522. // Xray status
  523. if s.xrayService.IsXrayRunning() {
  524. status.Xray.State = Running
  525. status.Xray.ErrorMsg = ""
  526. } else {
  527. err := s.xrayService.GetXrayErr()
  528. if err != nil {
  529. status.Xray.State = Error
  530. } else {
  531. status.Xray.State = Stop
  532. }
  533. status.Xray.ErrorMsg = s.xrayService.GetXrayResult()
  534. }
  535. status.Xray.Version = s.xrayService.GetXrayVersion()
  536. status.PanelVersion = config.GetVersion()
  537. if guid, err := s.settingService.GetPanelGuid(); err == nil {
  538. status.PanelGuid = guid
  539. }
  540. // Application stats
  541. var rtm runtime.MemStats
  542. runtime.ReadMemStats(&rtm)
  543. status.AppStats.Mem = rtm.Sys
  544. status.AppStats.Threads = uint32(runtime.NumGoroutine())
  545. if p != nil && p.IsRunning() {
  546. status.AppStats.Uptime = p.GetUptime()
  547. } else {
  548. status.AppStats.Uptime = 0
  549. }
  550. return status
  551. }
  552. // AppendCpuSample is preserved for callers that only have the CPU number.
  553. // New callers should prefer AppendStatusSample which writes the full set.
  554. func (s *ServerService) AppendCpuSample(t time.Time, v float64) {
  555. systemMetrics.append("cpu", t, v)
  556. }
  557. // AppendStatusSample writes one tick of every metric we keep — CPU, memory
  558. // percent, network throughput (bytes/s), online client count, and the three
  559. // load averages. Called by RefreshStatus on the same @2s cadence as
  560. // AppendCpuSample, so all series stay aligned.
  561. func (s *ServerService) AppendStatusSample(t time.Time, status *Status) {
  562. if status == nil {
  563. return
  564. }
  565. systemMetrics.append("cpu", t, status.Cpu)
  566. if status.Mem.Total > 0 {
  567. systemMetrics.append("mem", t, float64(status.Mem.Current)*100.0/float64(status.Mem.Total))
  568. }
  569. if status.Swap.Total > 0 {
  570. systemMetrics.append("swap", t, float64(status.Swap.Current)*100.0/float64(status.Swap.Total))
  571. } else {
  572. systemMetrics.append("swap", t, 0)
  573. }
  574. systemMetrics.append("netUp", t, float64(status.NetIO.Up))
  575. systemMetrics.append("netDown", t, float64(status.NetIO.Down))
  576. systemMetrics.append("diskRead", t, float64(status.DiskIO.Read))
  577. systemMetrics.append("diskWrite", t, float64(status.DiskIO.Write))
  578. if status.Disk.Total > 0 {
  579. systemMetrics.append("diskUsage", t, float64(status.Disk.Current)*100.0/float64(status.Disk.Total))
  580. }
  581. systemMetrics.append("pktUp", t, float64(status.NetIO.PktUp))
  582. systemMetrics.append("pktDown", t, float64(status.NetIO.PktDown))
  583. systemMetrics.append("tcpCount", t, float64(status.TcpCount))
  584. systemMetrics.append("udpCount", t, float64(status.UdpCount))
  585. online := 0
  586. if p != nil && p.IsRunning() {
  587. online = len(p.GetOnlineClients())
  588. }
  589. systemMetrics.append("online", t, float64(online))
  590. if len(status.Loads) >= 3 {
  591. systemMetrics.append("load1", t, status.Loads[0])
  592. systemMetrics.append("load5", t, status.Loads[1])
  593. systemMetrics.append("load15", t, status.Loads[2])
  594. }
  595. }
  596. func (s *ServerService) sampleCPUUtilization() (float64, error) {
  597. // Try native platform-specific CPU implementation first (Windows, Linux, macOS)
  598. if pct, err := sys.CPUPercentRaw(); err == nil {
  599. s.mu.Lock()
  600. // First call to native method returns 0 (initializes baseline)
  601. if !s.hasNativeCPUSample {
  602. s.hasNativeCPUSample = true
  603. s.mu.Unlock()
  604. return 0, nil
  605. }
  606. // Smooth with EMA
  607. const alpha = 0.3
  608. if s.emaCPU == 0 {
  609. s.emaCPU = pct
  610. } else {
  611. s.emaCPU = alpha*pct + (1-alpha)*s.emaCPU
  612. }
  613. val := s.emaCPU
  614. s.mu.Unlock()
  615. return val, nil
  616. }
  617. // If native call fails, fall back to gopsutil times
  618. // Read aggregate CPU times (all CPUs combined)
  619. times, err := cpu.Times(false)
  620. if err != nil {
  621. return 0, err
  622. }
  623. if len(times) == 0 {
  624. return 0, fmt.Errorf("no cpu times available")
  625. }
  626. cur := times[0]
  627. s.mu.Lock()
  628. defer s.mu.Unlock()
  629. // If this is the first sample, initialize and return current EMA (0 by default)
  630. if !s.hasLastCPUSample {
  631. s.lastCPUTimes = cur
  632. s.hasLastCPUSample = true
  633. return s.emaCPU, nil
  634. }
  635. // Compute busy and total deltas
  636. // Note: Guest and GuestNice times are already included in User and Nice respectively,
  637. // so we exclude them to avoid double-counting (Linux kernel accounting)
  638. idleDelta := cur.Idle - s.lastCPUTimes.Idle
  639. busyDelta := (cur.User - s.lastCPUTimes.User) +
  640. (cur.System - s.lastCPUTimes.System) +
  641. (cur.Nice - s.lastCPUTimes.Nice) +
  642. (cur.Iowait - s.lastCPUTimes.Iowait) +
  643. (cur.Irq - s.lastCPUTimes.Irq) +
  644. (cur.Softirq - s.lastCPUTimes.Softirq) +
  645. (cur.Steal - s.lastCPUTimes.Steal)
  646. totalDelta := busyDelta + idleDelta
  647. // Update last sample for next time
  648. s.lastCPUTimes = cur
  649. // Guard against division by zero or negative deltas (e.g., counter resets)
  650. if totalDelta <= 0 {
  651. return s.emaCPU, nil
  652. }
  653. raw := 100.0 * (busyDelta / totalDelta)
  654. if raw < 0 {
  655. raw = 0
  656. }
  657. if raw > 100 {
  658. raw = 100
  659. }
  660. // Exponential moving average to smooth spikes
  661. const alpha = 0.3 // smoothing factor (0<alpha<=1). Higher = more responsive, lower = smoother
  662. if s.emaCPU == 0 {
  663. // Initialize EMA with the first real reading to avoid long warm-up from zero
  664. s.emaCPU = raw
  665. } else {
  666. s.emaCPU = alpha*raw + (1-alpha)*s.emaCPU
  667. }
  668. return s.emaCPU, nil
  669. }
  670. const (
  671. maxXrayArchiveBytes = 200 << 20
  672. maxXrayBinaryBytes = 200 << 20
  673. // maxXrayDigestBytes caps the .dgst checksum sidecar read; it is a few
  674. // hundred bytes in practice.
  675. maxXrayDigestBytes = 64 << 10
  676. )
  677. func (s *ServerService) GetXrayVersions() ([]string, error) {
  678. const (
  679. XrayURL = "https://api.github.com/repos/XTLS/Xray-core/releases"
  680. bufferSize = 8192
  681. )
  682. resp, err := s.settingService.NewProxiedHTTPClient(10 * time.Second).Get(XrayURL)
  683. if err != nil {
  684. return nil, err
  685. }
  686. defer resp.Body.Close()
  687. // Check HTTP status code - GitHub API returns object instead of array on error
  688. if resp.StatusCode != http.StatusOK {
  689. bodyBytes, _ := io.ReadAll(resp.Body)
  690. var errorResponse struct {
  691. Message string `json:"message"`
  692. }
  693. if json.Unmarshal(bodyBytes, &errorResponse) == nil && errorResponse.Message != "" {
  694. return nil, fmt.Errorf("GitHub API error: %s", errorResponse.Message)
  695. }
  696. return nil, fmt.Errorf("GitHub API returned status %d: %s", resp.StatusCode, resp.Status)
  697. }
  698. buffer := bytes.NewBuffer(make([]byte, bufferSize))
  699. buffer.Reset()
  700. if _, err := buffer.ReadFrom(resp.Body); err != nil {
  701. return nil, err
  702. }
  703. var releases []Release
  704. if err := json.Unmarshal(buffer.Bytes(), &releases); err != nil {
  705. return nil, err
  706. }
  707. var versions []string
  708. for _, release := range releases {
  709. tagVersion := strings.TrimPrefix(release.TagName, "v")
  710. tagParts := strings.Split(tagVersion, ".")
  711. if len(tagParts) != 3 {
  712. continue
  713. }
  714. major, err1 := strconv.Atoi(tagParts[0])
  715. minor, err2 := strconv.Atoi(tagParts[1])
  716. patch, err3 := strconv.Atoi(tagParts[2])
  717. if err1 != nil || err2 != nil || err3 != nil {
  718. continue
  719. }
  720. if major > 26 || (major == 26 && minor > 4) || (major == 26 && minor == 4 && patch >= 25) {
  721. versions = append(versions, release.TagName)
  722. }
  723. }
  724. return versions, nil
  725. }
  726. func (s *ServerService) StopXrayService() error {
  727. err := s.xrayService.StopXray()
  728. if err != nil {
  729. logger.Error("stop xray failed:", err)
  730. return err
  731. }
  732. return nil
  733. }
  734. func (s *ServerService) RestartXrayService() error {
  735. err := s.xrayService.RestartXray(true)
  736. if err != nil {
  737. logger.Error("start xray failed:", err)
  738. return err
  739. }
  740. return nil
  741. }
  742. func (s *ServerService) downloadXRay(version string) (string, error) {
  743. osName := runtime.GOOS
  744. arch := runtime.GOARCH
  745. switch osName {
  746. case "darwin":
  747. osName = "macos"
  748. case "windows":
  749. osName = "windows"
  750. }
  751. switch arch {
  752. case "amd64":
  753. arch = "64"
  754. case "arm64":
  755. arch = "arm64-v8a"
  756. case "armv7":
  757. arch = "arm32-v7a"
  758. case "armv6":
  759. arch = "arm32-v6"
  760. case "armv5":
  761. arch = "arm32-v5"
  762. case "386":
  763. arch = "32"
  764. case "s390x":
  765. arch = "s390x"
  766. }
  767. fileName := fmt.Sprintf("Xray-%s-%s.zip", osName, arch)
  768. url := fmt.Sprintf("https://github.com/XTLS/Xray-core/releases/download/%s/%s", version, fileName)
  769. client := s.settingService.NewProxiedHTTPClient(60 * time.Second)
  770. resp, err := client.Get(url)
  771. if err != nil {
  772. return "", err
  773. }
  774. defer resp.Body.Close()
  775. if resp.StatusCode != http.StatusOK {
  776. return "", fmt.Errorf("download xray: unexpected HTTP %d", resp.StatusCode)
  777. }
  778. if resp.ContentLength > maxXrayArchiveBytes {
  779. return "", fmt.Errorf("download xray: archive exceeds %d bytes", maxXrayArchiveBytes)
  780. }
  781. file, err := os.CreateTemp("", "xray-*.zip")
  782. if err != nil {
  783. return "", err
  784. }
  785. path := file.Name()
  786. ok := false
  787. defer func() {
  788. _ = file.Close()
  789. if !ok {
  790. _ = os.Remove(path)
  791. }
  792. }()
  793. n, err := io.Copy(file, io.LimitReader(resp.Body, maxXrayArchiveBytes+1))
  794. if err != nil {
  795. return "", err
  796. }
  797. if n > maxXrayArchiveBytes {
  798. return "", fmt.Errorf("download xray: archive exceeds %d bytes", maxXrayArchiveBytes)
  799. }
  800. // Verify the archive against the SHA2-256 published in the release's .dgst
  801. // sidecar before installing it. TLS protects the transport, not the artifact;
  802. // a corrupted or tampered asset must not be installed and run as xray.
  803. want, err := s.fetchXrayDigestSHA256(client, url+".dgst")
  804. if err != nil {
  805. return "", err
  806. }
  807. if _, err := file.Seek(0, io.SeekStart); err != nil {
  808. return "", err
  809. }
  810. hasher := sha256.New()
  811. if _, err := io.Copy(hasher, file); err != nil {
  812. return "", err
  813. }
  814. if got := hex.EncodeToString(hasher.Sum(nil)); !strings.EqualFold(got, want) {
  815. // User-facing warning: the archive's SHA-256 does not match the official
  816. // release checksum, so the download is corrupted or has been tampered
  817. // with. Abort the install so a bad binary is never run, and tell the user
  818. // to retry/re-download rather than proceed with a mismatched image.
  819. return "", fmt.Errorf("Xray update aborted: the downloaded archive does not match the official SHA-256 checksum, so the image is corrupted or differs from the official release. Please exit and re-download the official image, then try again (expected %s, got %s)", want, got)
  820. }
  821. ok = true
  822. return path, nil
  823. }
  824. // fetchXrayDigestSHA256 downloads the .dgst sidecar XTLS publishes next to each
  825. // release asset and returns the SHA2-256 hex digest it lists.
  826. func (s *ServerService) fetchXrayDigestSHA256(client *http.Client, dgstURL string) (string, error) {
  827. resp, err := client.Get(dgstURL)
  828. if err != nil {
  829. return "", fmt.Errorf("download xray checksum: %w", err)
  830. }
  831. defer resp.Body.Close()
  832. if resp.StatusCode != http.StatusOK {
  833. return "", fmt.Errorf("download xray checksum: unexpected HTTP %d", resp.StatusCode)
  834. }
  835. raw, err := io.ReadAll(io.LimitReader(resp.Body, maxXrayDigestBytes))
  836. if err != nil {
  837. return "", fmt.Errorf("download xray checksum: %w", err)
  838. }
  839. return parseXrayDigestSHA256(raw)
  840. }
  841. // parseXrayDigestSHA256 extracts the lowercase SHA2-256 hex from an XTLS .dgst
  842. // file, whose lines are "ALGO= <hex>" (the relevant one being "SHA2-256= ...").
  843. func parseXrayDigestSHA256(dgst []byte) (string, error) {
  844. for _, line := range strings.Split(string(dgst), "\n") {
  845. rest, ok := strings.CutPrefix(strings.TrimSpace(line), "SHA2-256=")
  846. if !ok {
  847. continue
  848. }
  849. h := strings.ToLower(strings.TrimSpace(rest))
  850. if len(h) != 64 {
  851. return "", fmt.Errorf("xray checksum: malformed SHA2-256 entry in digest")
  852. }
  853. return h, nil
  854. }
  855. return "", fmt.Errorf("xray checksum: no SHA2-256 entry in digest")
  856. }
  857. func (s *ServerService) UpdateXray(version string) error {
  858. versions, err := s.GetXrayVersions()
  859. if err != nil {
  860. return err
  861. }
  862. if !slices.Contains(versions, version) {
  863. return fmt.Errorf("xray version %q is not in the fetched release list", version)
  864. }
  865. // 1. Stop xray before doing anything
  866. if err := s.StopXrayService(); err != nil {
  867. logger.Warning("failed to stop xray before update:", err)
  868. }
  869. // 2. Download the zip
  870. zipFileName, err := s.downloadXRay(version)
  871. if err != nil {
  872. return err
  873. }
  874. defer os.Remove(zipFileName)
  875. zipFile, err := os.Open(zipFileName)
  876. if err != nil {
  877. return err
  878. }
  879. defer zipFile.Close()
  880. stat, err := zipFile.Stat()
  881. if err != nil {
  882. return err
  883. }
  884. reader, err := zip.NewReader(zipFile, stat.Size())
  885. if err != nil {
  886. return err
  887. }
  888. // 3. Helper to extract files
  889. copyZipFile := func(zipName string, fileName string) error {
  890. zipFile, err := reader.Open(zipName)
  891. if err != nil {
  892. return err
  893. }
  894. defer zipFile.Close()
  895. if err := os.MkdirAll(filepath.Dir(fileName), 0755); err != nil {
  896. return err
  897. }
  898. tmpFile, err := os.CreateTemp(filepath.Dir(fileName), ".xray-*")
  899. if err != nil {
  900. return err
  901. }
  902. tmpPath := tmpFile.Name()
  903. ok := false
  904. defer func() {
  905. _ = tmpFile.Close()
  906. if !ok {
  907. _ = os.Remove(tmpPath)
  908. }
  909. }()
  910. n, err := io.Copy(tmpFile, io.LimitReader(zipFile, maxXrayBinaryBytes+1))
  911. if err != nil {
  912. return err
  913. }
  914. if n > maxXrayBinaryBytes {
  915. return fmt.Errorf("xray binary exceeds %d bytes", maxXrayBinaryBytes)
  916. }
  917. if err := tmpFile.Chmod(0755); err != nil {
  918. return err
  919. }
  920. if err := tmpFile.Close(); err != nil {
  921. return err
  922. }
  923. if runtime.GOOS == "windows" {
  924. _ = os.Remove(fileName)
  925. }
  926. if err := os.Rename(tmpPath, fileName); err != nil {
  927. return err
  928. }
  929. ok = true
  930. return nil
  931. }
  932. // 4. Extract correct binary
  933. if runtime.GOOS == "windows" {
  934. targetBinary := filepath.Join(config.GetBinFolderPath(), "xray-windows-amd64.exe")
  935. err = copyZipFile("xray.exe", targetBinary)
  936. } else {
  937. err = copyZipFile("xray", xray.GetBinaryPath())
  938. }
  939. if err != nil {
  940. return err
  941. }
  942. // 5. Restart xray
  943. if err := s.xrayService.RestartXray(true); err != nil {
  944. logger.Error("start xray failed:", err)
  945. return err
  946. }
  947. return nil
  948. }
  949. func (s *ServerService) GetLogs(count string, level string, syslog string) []string {
  950. c, _ := strconv.Atoi(count)
  951. var lines []string
  952. if syslog == "true" {
  953. // Check if running on Windows - journalctl is not available
  954. if runtime.GOOS == "windows" {
  955. return []string{"Syslog is not supported on Windows. Please use application logs instead by unchecking the 'Syslog' option."}
  956. }
  957. // Validate and sanitize count parameter
  958. countInt, err := strconv.Atoi(count)
  959. if err != nil || countInt < 1 || countInt > 10000 {
  960. return []string{"Invalid count parameter - must be a number between 1 and 10000"}
  961. }
  962. // Validate level parameter - only allow valid syslog levels
  963. validLevels := map[string]bool{
  964. "0": true, "emerg": true,
  965. "1": true, "alert": true,
  966. "2": true, "crit": true,
  967. "3": true, "err": true,
  968. "4": true, "warning": true,
  969. "5": true, "notice": true,
  970. "6": true, "info": true,
  971. "7": true, "debug": true,
  972. }
  973. if !validLevels[level] {
  974. return []string{"Invalid level parameter - must be a valid syslog level"}
  975. }
  976. // Use hardcoded command with validated parameters
  977. cmd := exec.Command("journalctl", "-u", "x-ui", "--no-pager", "-n", strconv.Itoa(countInt), "-p", level)
  978. var out bytes.Buffer
  979. cmd.Stdout = &out
  980. err = cmd.Run()
  981. if err != nil {
  982. return []string{"Failed to run journalctl command! Make sure systemd is available and x-ui service is registered."}
  983. }
  984. lines = strings.Split(out.String(), "\n")
  985. } else {
  986. lines = logger.GetLogs(c, level)
  987. }
  988. return lines
  989. }
  990. func (s *ServerService) GetXrayLogs(
  991. count string,
  992. filter string,
  993. showDirect string,
  994. showBlocked string,
  995. showProxy string,
  996. freedoms []string,
  997. blackholes []string) []LogEntry {
  998. const (
  999. Direct = iota
  1000. Blocked
  1001. Proxied
  1002. )
  1003. countInt, _ := strconv.Atoi(count)
  1004. var entries []LogEntry
  1005. pathToAccessLog, err := xray.GetAccessLogPath()
  1006. if err != nil {
  1007. return nil
  1008. }
  1009. file, err := os.Open(pathToAccessLog)
  1010. if err != nil {
  1011. return nil
  1012. }
  1013. defer file.Close()
  1014. scanner := bufio.NewScanner(file)
  1015. for scanner.Scan() {
  1016. line := strings.TrimSpace(scanner.Text())
  1017. if line == "" || strings.Contains(line, "api -> api") {
  1018. //skipping empty lines and api calls
  1019. continue
  1020. }
  1021. if filter != "" && !strings.Contains(line, filter) {
  1022. //applying filter if it's not empty
  1023. continue
  1024. }
  1025. var entry LogEntry
  1026. parts := strings.Fields(line)
  1027. for i, part := range parts {
  1028. if i == 0 {
  1029. dateTime, err := time.ParseInLocation("2006/01/02 15:04:05.999999", parts[0]+" "+parts[1], time.Local)
  1030. if err != nil {
  1031. continue
  1032. }
  1033. entry.DateTime = dateTime.UTC()
  1034. }
  1035. if part == "from" {
  1036. entry.FromAddress = strings.TrimLeft(parts[i+1], "/")
  1037. } else if part == "accepted" {
  1038. entry.ToAddress = strings.TrimLeft(parts[i+1], "/")
  1039. } else if strings.HasPrefix(part, "[") {
  1040. entry.Inbound = part[1:]
  1041. } else if strings.HasSuffix(part, "]") {
  1042. entry.Outbound = part[:len(part)-1]
  1043. } else if part == "email:" {
  1044. entry.Email = parts[i+1]
  1045. }
  1046. }
  1047. if logEntryContains(line, freedoms) {
  1048. if showDirect == "false" {
  1049. continue
  1050. }
  1051. entry.Event = Direct
  1052. } else if logEntryContains(line, blackholes) {
  1053. if showBlocked == "false" {
  1054. continue
  1055. }
  1056. entry.Event = Blocked
  1057. } else {
  1058. if showProxy == "false" {
  1059. continue
  1060. }
  1061. entry.Event = Proxied
  1062. }
  1063. entries = append(entries, entry)
  1064. }
  1065. if err := scanner.Err(); err != nil {
  1066. return nil
  1067. }
  1068. if len(entries) > countInt {
  1069. entries = entries[len(entries)-countInt:]
  1070. }
  1071. return entries
  1072. }
  1073. // isVirtualInterface returns true for loopback and virtual/tunnel interfaces
  1074. // that should be excluded from network traffic statistics.
  1075. func isVirtualInterface(name string) bool {
  1076. // Exact matches
  1077. if name == "lo" || name == "lo0" {
  1078. return true
  1079. }
  1080. // Prefix matches for virtual/tunnel interfaces
  1081. virtualPrefixes := []string{
  1082. "loopback",
  1083. "docker",
  1084. "br-",
  1085. "veth",
  1086. "virbr",
  1087. "tun",
  1088. "tap",
  1089. "wg",
  1090. "tailscale",
  1091. "zt",
  1092. }
  1093. for _, prefix := range virtualPrefixes {
  1094. if strings.HasPrefix(name, prefix) {
  1095. return true
  1096. }
  1097. }
  1098. return false
  1099. }
  1100. func logEntryContains(line string, suffixes []string) bool {
  1101. for _, sfx := range suffixes {
  1102. if strings.Contains(line, sfx+"]") {
  1103. return true
  1104. }
  1105. }
  1106. return false
  1107. }
  1108. func (s *ServerService) GetConfigJson() (any, error) {
  1109. config, err := s.xrayService.GetXrayConfig()
  1110. if err != nil {
  1111. return nil, err
  1112. }
  1113. contents, err := json.MarshalIndent(config, "", " ")
  1114. if err != nil {
  1115. return nil, err
  1116. }
  1117. var jsonData any
  1118. err = json.Unmarshal(contents, &jsonData)
  1119. if err != nil {
  1120. return nil, err
  1121. }
  1122. return jsonData, nil
  1123. }
  1124. func (s *ServerService) GetDb() ([]byte, error) {
  1125. if database.IsPostgres() {
  1126. return s.exportPostgresDB()
  1127. }
  1128. // Update by manually trigger a checkpoint operation
  1129. err := database.Checkpoint()
  1130. if err != nil {
  1131. return nil, err
  1132. }
  1133. // Open the file for reading
  1134. file, err := os.Open(config.GetDBPath())
  1135. if err != nil {
  1136. return nil, err
  1137. }
  1138. defer file.Close()
  1139. // Read the file contents
  1140. fileContents, err := io.ReadAll(file)
  1141. if err != nil {
  1142. return nil, err
  1143. }
  1144. return fileContents, nil
  1145. }
  1146. // BackupFilename returns the filename for a database backup, named after the
  1147. // panel's address — the configured web domain, or the server's public IP when
  1148. // no domain is set — so a downloaded or Telegram-sent backup identifies the
  1149. // server it came from. The extension is .dump on PostgreSQL and .db on SQLite;
  1150. // the base falls back to "x-ui" when no address is known.
  1151. func (s *ServerService) BackupFilename() string {
  1152. ext := ".db"
  1153. if database.IsPostgres() {
  1154. ext = ".dump"
  1155. }
  1156. return s.backupHost() + ext
  1157. }
  1158. // backupHost picks the address used to name backup files, preferring the
  1159. // configured web domain and otherwise the cached public IP (IPv4 before IPv6),
  1160. // reduced to safe filename characters.
  1161. func (s *ServerService) backupHost() string {
  1162. host := ""
  1163. if domain, err := s.settingService.GetWebDomain(); err == nil {
  1164. host = strings.TrimSpace(domain)
  1165. }
  1166. if host == "" {
  1167. if st := s.LastStatus(); st != nil {
  1168. if ip := st.PublicIP.IPv4; ip != "" && ip != "N/A" {
  1169. host = ip
  1170. } else if ip := st.PublicIP.IPv6; ip != "" && ip != "N/A" {
  1171. host = ip
  1172. }
  1173. }
  1174. }
  1175. return sanitizeBackupHost(host)
  1176. }
  1177. // sanitizeBackupHost reduces a host to characters safe in a download filename
  1178. // (the getDb handler enforces ^[a-zA-Z0-9_\-.]+$). IPv6 brackets are stripped
  1179. // and any other character — such as the colons in an IPv6 address — becomes a
  1180. // hyphen. Returns "x-ui" when nothing usable remains.
  1181. func sanitizeBackupHost(host string) string {
  1182. host = strings.Trim(host, "[]")
  1183. var b strings.Builder
  1184. for _, r := range host {
  1185. switch {
  1186. case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '.', r == '-', r == '_':
  1187. b.WriteRune(r)
  1188. default:
  1189. b.WriteRune('-')
  1190. }
  1191. }
  1192. out := strings.Trim(b.String(), ".-")
  1193. if out == "" {
  1194. return "x-ui"
  1195. }
  1196. return out
  1197. }
  1198. // GetMigration produces a cross-engine migration file plus its filename: on a
  1199. // SQLite panel it returns a portable .dump (SQL text), and on a PostgreSQL panel
  1200. // it returns a .db SQLite database built from the live data. Either output can
  1201. // then seed a panel running on the other backend.
  1202. func (s *ServerService) GetMigration() ([]byte, string, error) {
  1203. if database.IsPostgres() {
  1204. tmp, err := os.CreateTemp("", "x-ui-migration-*.db")
  1205. if err != nil {
  1206. return nil, "", err
  1207. }
  1208. tmpPath := tmp.Name()
  1209. tmp.Close()
  1210. defer os.Remove(tmpPath)
  1211. if err := database.ExportPostgresToSQLite(config.GetDBDSN(), tmpPath); err != nil {
  1212. return nil, "", err
  1213. }
  1214. data, err := os.ReadFile(tmpPath)
  1215. if err != nil {
  1216. return nil, "", err
  1217. }
  1218. return data, "x-ui.db", nil
  1219. }
  1220. // SQLite panel: checkpoint so the .db reflects the latest writes, then dump.
  1221. if err := database.Checkpoint(); err != nil {
  1222. return nil, "", err
  1223. }
  1224. data, err := database.DumpSQLiteToBytes(config.GetDBPath())
  1225. if err != nil {
  1226. return nil, "", err
  1227. }
  1228. return data, "x-ui.dump", nil
  1229. }
  1230. func (s *ServerService) ImportDB(file multipart.File) error {
  1231. if database.IsPostgres() {
  1232. return s.importPostgresDB(file)
  1233. }
  1234. // Check if the file is a SQLite database
  1235. isValidDb, err := database.IsSQLiteDB(file)
  1236. if err != nil {
  1237. return common.NewErrorf("Error checking db file format: %v", err)
  1238. }
  1239. if !isValidDb {
  1240. return common.NewError("Invalid db file format")
  1241. }
  1242. // Reset the file reader to the beginning
  1243. _, err = file.Seek(0, 0)
  1244. if err != nil {
  1245. return common.NewErrorf("Error resetting file reader: %v", err)
  1246. }
  1247. // Save the file as a temporary file
  1248. tempPath := fmt.Sprintf("%s.temp", config.GetDBPath())
  1249. // Remove the existing temporary file (if any)
  1250. if _, err := os.Stat(tempPath); err == nil {
  1251. if errRemove := os.Remove(tempPath); errRemove != nil {
  1252. return common.NewErrorf("Error removing existing temporary db file: %v", errRemove)
  1253. }
  1254. }
  1255. // Create the temporary file
  1256. tempFile, err := os.Create(tempPath)
  1257. if err != nil {
  1258. return common.NewErrorf("Error creating temporary db file: %v", err)
  1259. }
  1260. // Robust deferred cleanup for the temporary file
  1261. defer func() {
  1262. if tempFile != nil {
  1263. if cerr := tempFile.Close(); cerr != nil {
  1264. logger.Warningf("Warning: failed to close temp file: %v", cerr)
  1265. }
  1266. }
  1267. if _, err := os.Stat(tempPath); err == nil {
  1268. if rerr := os.Remove(tempPath); rerr != nil {
  1269. logger.Warningf("Warning: failed to remove temp file: %v", rerr)
  1270. }
  1271. }
  1272. }()
  1273. // Save uploaded file to temporary file
  1274. if _, err = io.Copy(tempFile, file); err != nil {
  1275. return common.NewErrorf("Error saving db: %v", err)
  1276. }
  1277. // Close temp file before opening via sqlite
  1278. if err = tempFile.Close(); err != nil {
  1279. return common.NewErrorf("Error closing temporary db file: %v", err)
  1280. }
  1281. tempFile = nil
  1282. // Validate integrity (no migrations / side effects)
  1283. if err = database.ValidateSQLiteDB(tempPath); err != nil {
  1284. return common.NewErrorf("Invalid or corrupt db file: %v", err)
  1285. }
  1286. xrayStopped := true
  1287. defer func() {
  1288. if xrayStopped {
  1289. if errR := s.RestartXrayService(); errR != nil {
  1290. logger.Warningf("Failed to restart Xray after DB import error: %v", errR)
  1291. }
  1292. }
  1293. }()
  1294. if errStop := s.StopXrayService(); errStop != nil {
  1295. logger.Warningf("Failed to stop Xray before DB import: %v", errStop)
  1296. }
  1297. if errClose := database.CloseDB(); errClose != nil {
  1298. logger.Warningf("Failed to close existing DB before replacement: %v", errClose)
  1299. }
  1300. // Backup the current database for fallback
  1301. fallbackPath := fmt.Sprintf("%s.backup", config.GetDBPath())
  1302. // Remove the existing fallback file (if any)
  1303. if _, err := os.Stat(fallbackPath); err == nil {
  1304. if errRemove := os.Remove(fallbackPath); errRemove != nil {
  1305. return common.NewErrorf("Error removing existing fallback db file: %v", errRemove)
  1306. }
  1307. }
  1308. // Move the current database to the fallback location
  1309. if err = os.Rename(config.GetDBPath(), fallbackPath); err != nil {
  1310. return common.NewErrorf("Error backing up current db file: %v", err)
  1311. }
  1312. // Defer fallback cleanup ONLY if everything goes well
  1313. defer func() {
  1314. if _, err := os.Stat(fallbackPath); err == nil {
  1315. if rerr := os.Remove(fallbackPath); rerr != nil {
  1316. logger.Warningf("Warning: failed to remove fallback file: %v", rerr)
  1317. }
  1318. }
  1319. }()
  1320. // Move temp to DB path
  1321. if err = os.Rename(tempPath, config.GetDBPath()); err != nil {
  1322. // Restore from fallback
  1323. if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
  1324. return common.NewErrorf("Error moving db file and restoring fallback: %v", errRename)
  1325. }
  1326. return common.NewErrorf("Error moving db file: %v", err)
  1327. }
  1328. // Open & migrate new DB
  1329. if err = database.InitDB(config.GetDBPath()); err != nil {
  1330. if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
  1331. return common.NewErrorf("Error migrating db and restoring fallback: %v", errRename)
  1332. }
  1333. return common.NewErrorf("Error migrating db: %v", err)
  1334. }
  1335. s.inboundService.MigrateDB()
  1336. xrayStopped = false
  1337. if err = s.RestartXrayService(); err != nil {
  1338. return common.NewErrorf("Imported DB but failed to start Xray: %v", err)
  1339. }
  1340. return nil
  1341. }
  1342. // pgConnEnv turns the configured PostgreSQL DSN into the PG* environment used by
  1343. // pg_dump/pg_restore, keeping the password out of the process argument list.
  1344. func pgConnEnv(dsn string) (env []string, dbname string, err error) {
  1345. u, err := url.Parse(strings.TrimSpace(dsn))
  1346. if err != nil {
  1347. return nil, "", err
  1348. }
  1349. if u.Scheme != "postgres" && u.Scheme != "postgresql" {
  1350. return nil, "", common.NewErrorf("unsupported DSN scheme %q", u.Scheme)
  1351. }
  1352. dbname = strings.TrimPrefix(u.Path, "/")
  1353. if dbname == "" {
  1354. return nil, "", common.NewError("PostgreSQL DSN is missing a database name")
  1355. }
  1356. host := u.Hostname()
  1357. if host == "" {
  1358. host = "127.0.0.1"
  1359. }
  1360. port := u.Port()
  1361. if port == "" {
  1362. port = "5432"
  1363. }
  1364. env = append(os.Environ(), "PGHOST="+host, "PGPORT="+port, "PGDATABASE="+dbname)
  1365. if user := u.User.Username(); user != "" {
  1366. env = append(env, "PGUSER="+user)
  1367. }
  1368. if pass, ok := u.User.Password(); ok {
  1369. env = append(env, "PGPASSWORD="+pass)
  1370. }
  1371. if sslmode := u.Query().Get("sslmode"); sslmode != "" {
  1372. env = append(env, "PGSSLMODE="+sslmode)
  1373. }
  1374. return env, dbname, nil
  1375. }
  1376. func (s *ServerService) exportPostgresDB() ([]byte, error) {
  1377. bin, err := exec.LookPath("pg_dump")
  1378. if err != nil {
  1379. return nil, common.NewError("pg_dump not found on the server; install the postgresql-client package to back up a PostgreSQL database")
  1380. }
  1381. env, dbname, err := pgConnEnv(config.GetDBDSN())
  1382. if err != nil {
  1383. return nil, common.NewErrorf("invalid PostgreSQL DSN: %v", err)
  1384. }
  1385. cmd := exec.Command(bin, "--format=custom", "--no-owner", "--no-privileges", "--dbname", dbname)
  1386. cmd.Env = env
  1387. var out, stderr bytes.Buffer
  1388. cmd.Stdout = &out
  1389. cmd.Stderr = &stderr
  1390. if err := cmd.Run(); err != nil {
  1391. return nil, common.NewErrorf("pg_dump failed: %v: %s", err, strings.TrimSpace(stderr.String()))
  1392. }
  1393. return out.Bytes(), nil
  1394. }
  1395. func (s *ServerService) importPostgresDB(file multipart.File) error {
  1396. header := make([]byte, 5)
  1397. if _, err := file.ReadAt(header, 0); err != nil {
  1398. return common.NewErrorf("Error reading dump file: %v", err)
  1399. }
  1400. if string(header) != "PGDMP" {
  1401. return common.NewError("Invalid file: expected a PostgreSQL custom-format dump (.dump) created by this panel's Back Up")
  1402. }
  1403. if _, err := file.Seek(0, 0); err != nil {
  1404. return common.NewErrorf("Error resetting file reader: %v", err)
  1405. }
  1406. bin, err := exec.LookPath("pg_restore")
  1407. if err != nil {
  1408. return common.NewError("pg_restore not found on the server; install the postgresql-client package to restore a PostgreSQL database")
  1409. }
  1410. env, dbname, err := pgConnEnv(config.GetDBDSN())
  1411. if err != nil {
  1412. return common.NewErrorf("invalid PostgreSQL DSN: %v", err)
  1413. }
  1414. tempFile, err := os.CreateTemp("", "x-ui-pg-restore-*.dump")
  1415. if err != nil {
  1416. return common.NewErrorf("Error creating temporary dump file: %v", err)
  1417. }
  1418. tempPath := tempFile.Name()
  1419. defer os.Remove(tempPath)
  1420. if _, err := io.Copy(tempFile, file); err != nil {
  1421. tempFile.Close()
  1422. return common.NewErrorf("Error saving dump: %v", err)
  1423. }
  1424. if err := tempFile.Close(); err != nil {
  1425. return common.NewErrorf("Error closing temporary dump file: %v", err)
  1426. }
  1427. xrayStopped := true
  1428. defer func() {
  1429. if xrayStopped {
  1430. if errR := s.RestartXrayService(); errR != nil {
  1431. logger.Warningf("Failed to restart Xray after DB restore error: %v", errR)
  1432. }
  1433. }
  1434. }()
  1435. if errStop := s.StopXrayService(); errStop != nil {
  1436. logger.Warningf("Failed to stop Xray before DB restore: %v", errStop)
  1437. }
  1438. if errClose := database.CloseDB(); errClose != nil {
  1439. logger.Warningf("Failed to close existing DB before restore: %v", errClose)
  1440. }
  1441. cmd := exec.Command(bin,
  1442. "--clean", "--if-exists", "--no-owner", "--no-privileges",
  1443. "--single-transaction", "--dbname", dbname, tempPath,
  1444. )
  1445. cmd.Env = env
  1446. var stderr bytes.Buffer
  1447. cmd.Stderr = &stderr
  1448. runErr := cmd.Run()
  1449. if errInit := database.InitDB(config.GetDBPath()); errInit != nil {
  1450. return common.NewErrorf("Restore finished but reopening the database failed: %v", errInit)
  1451. }
  1452. s.inboundService.MigrateDB()
  1453. if runErr != nil {
  1454. return common.NewErrorf("pg_restore failed (database left unchanged): %v: %s", runErr, strings.TrimSpace(stderr.String()))
  1455. }
  1456. xrayStopped = false
  1457. if err := s.RestartXrayService(); err != nil {
  1458. return common.NewErrorf("Restored DB but failed to start Xray: %v", err)
  1459. }
  1460. return nil
  1461. }
  1462. // IsValidGeofileName validates that the filename is safe for geofile operations.
  1463. // It checks for path traversal attempts and ensures the filename contains only safe characters.
  1464. func (s *ServerService) IsValidGeofileName(filename string) bool {
  1465. if filename == "" {
  1466. return false
  1467. }
  1468. // Check for path traversal attempts
  1469. if strings.Contains(filename, "..") {
  1470. return false
  1471. }
  1472. // Check for path separators (both forward and backward slash)
  1473. if strings.ContainsAny(filename, `/\`) {
  1474. return false
  1475. }
  1476. // Check for absolute path indicators
  1477. if filepath.IsAbs(filename) {
  1478. return false
  1479. }
  1480. // Additional security: only allow alphanumeric, dots, underscores, and hyphens
  1481. // This is stricter than the general filename regex
  1482. validGeofilePattern := `^[a-zA-Z0-9._-]+\.dat$`
  1483. matched, _ := regexp.MatchString(validGeofilePattern, filename)
  1484. return matched
  1485. }
  1486. func (s *ServerService) UpdateGeofile(fileName string) error {
  1487. type geofileEntry struct {
  1488. URL string
  1489. FileName string
  1490. }
  1491. geofileAllowlist := map[string]geofileEntry{
  1492. "geoip.dat": {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip.dat"},
  1493. "geosite.dat": {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite.dat"},
  1494. "geoip_IR.dat": {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geoip.dat", "geoip_IR.dat"},
  1495. "geosite_IR.dat": {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat", "geosite_IR.dat"},
  1496. "geoip_RU.dat": {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip_RU.dat"},
  1497. "geosite_RU.dat": {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite_RU.dat"},
  1498. }
  1499. // Strict allowlist check to avoid writing uncontrolled files
  1500. if fileName != "" {
  1501. if _, ok := geofileAllowlist[fileName]; !ok {
  1502. return common.NewErrorf("Invalid geofile name: %q not in allowlist", fileName)
  1503. }
  1504. }
  1505. client := s.settingService.NewProxiedHTTPClient(0)
  1506. downloadFile := func(url, destPath string) error {
  1507. var req *http.Request
  1508. req, err := http.NewRequest("GET", url, nil)
  1509. if err != nil {
  1510. return common.NewErrorf("Failed to create HTTP request for %s: %v", url, err)
  1511. }
  1512. var localFileModTime time.Time
  1513. if fileInfo, err := os.Stat(destPath); err == nil {
  1514. localFileModTime = fileInfo.ModTime()
  1515. if !localFileModTime.IsZero() {
  1516. req.Header.Set("If-Modified-Since", localFileModTime.UTC().Format(http.TimeFormat))
  1517. }
  1518. }
  1519. resp, err := client.Do(req)
  1520. if err != nil {
  1521. return common.NewErrorf("Failed to download Geofile from %s: %v", url, err)
  1522. }
  1523. defer resp.Body.Close()
  1524. // Parse Last-Modified header from server
  1525. var serverModTime time.Time
  1526. serverModTimeStr := resp.Header.Get("Last-Modified")
  1527. if serverModTimeStr != "" {
  1528. parsedTime, err := time.Parse(http.TimeFormat, serverModTimeStr)
  1529. if err != nil {
  1530. logger.Warningf("Failed to parse Last-Modified header for %s: %v", url, err)
  1531. } else {
  1532. serverModTime = parsedTime
  1533. }
  1534. }
  1535. // Function to update local file's modification time
  1536. updateFileModTime := func() {
  1537. if !serverModTime.IsZero() {
  1538. if err := os.Chtimes(destPath, serverModTime, serverModTime); err != nil {
  1539. logger.Warningf("Failed to update modification time for %s: %v", destPath, err)
  1540. }
  1541. }
  1542. }
  1543. // Handle 304 Not Modified
  1544. if resp.StatusCode == http.StatusNotModified {
  1545. updateFileModTime()
  1546. return nil
  1547. }
  1548. if resp.StatusCode != http.StatusOK {
  1549. return common.NewErrorf("Failed to download Geofile from %s: received status code %d", url, resp.StatusCode)
  1550. }
  1551. file, err := os.Create(destPath)
  1552. if err != nil {
  1553. return common.NewErrorf("Failed to create Geofile %s: %v", destPath, err)
  1554. }
  1555. defer file.Close()
  1556. _, err = io.Copy(file, resp.Body)
  1557. if err != nil {
  1558. return common.NewErrorf("Failed to save Geofile %s: %v", destPath, err)
  1559. }
  1560. updateFileModTime()
  1561. return nil
  1562. }
  1563. var errorMessages []string
  1564. if fileName == "" {
  1565. // Download all geofiles
  1566. for _, entry := range geofileAllowlist {
  1567. destPath := filepath.Join(config.GetBinFolderPath(), entry.FileName)
  1568. if err := downloadFile(entry.URL, destPath); err != nil {
  1569. errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", entry.FileName, err))
  1570. }
  1571. }
  1572. } else {
  1573. entry := geofileAllowlist[fileName]
  1574. destPath := filepath.Join(config.GetBinFolderPath(), entry.FileName)
  1575. if err := downloadFile(entry.URL, destPath); err != nil {
  1576. errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", entry.FileName, err))
  1577. }
  1578. }
  1579. err := s.RestartXrayService()
  1580. if err != nil {
  1581. errorMessages = append(errorMessages, fmt.Sprintf("Updated Geofile '%s' but Failed to start Xray: %v", fileName, err))
  1582. }
  1583. if len(errorMessages) > 0 {
  1584. return common.NewErrorf("%s", strings.Join(errorMessages, "\r\n"))
  1585. }
  1586. return nil
  1587. }
  1588. func (s *ServerService) GetNewX25519Cert() (any, error) {
  1589. // Run the command
  1590. cmd := exec.Command(xray.GetBinaryPath(), "x25519")
  1591. var out bytes.Buffer
  1592. cmd.Stdout = &out
  1593. err := cmd.Run()
  1594. if err != nil {
  1595. return nil, err
  1596. }
  1597. lines := strings.Split(out.String(), "\n")
  1598. privateKeyLine := strings.Split(lines[0], ":")
  1599. publicKeyLine := strings.Split(lines[1], ":")
  1600. privateKey := strings.TrimSpace(privateKeyLine[1])
  1601. publicKey := strings.TrimSpace(publicKeyLine[1])
  1602. keyPair := map[string]any{
  1603. "privateKey": privateKey,
  1604. "publicKey": publicKey,
  1605. }
  1606. return keyPair, nil
  1607. }
  1608. func (s *ServerService) GetNewmldsa65() (any, error) {
  1609. // Run the command
  1610. cmd := exec.Command(xray.GetBinaryPath(), "mldsa65")
  1611. var out bytes.Buffer
  1612. cmd.Stdout = &out
  1613. err := cmd.Run()
  1614. if err != nil {
  1615. return nil, err
  1616. }
  1617. lines := strings.Split(out.String(), "\n")
  1618. SeedLine := strings.Split(lines[0], ":")
  1619. VerifyLine := strings.Split(lines[1], ":")
  1620. seed := strings.TrimSpace(SeedLine[1])
  1621. verify := strings.TrimSpace(VerifyLine[1])
  1622. keyPair := map[string]any{
  1623. "seed": seed,
  1624. "verify": verify,
  1625. }
  1626. return keyPair, nil
  1627. }
  1628. // GetCertHash parses a certificate (from a file path or inline PEM/DER content)
  1629. // and returns the hex-encoded SHA-256 over each certificate's raw DER — the
  1630. // value xray-core's pinnedPeerCertSha256 (pcs) expects. Lets the panel fill the
  1631. // pinned-cert field from the inbound's own certificate without the user
  1632. // computing the hash by hand.
  1633. func (s *ServerService) GetCertHash(certFile string, certContent string) ([]string, error) {
  1634. var certBytes []byte
  1635. if path := strings.TrimSpace(certFile); path != "" {
  1636. // Guard against path traversal: only hash certificate files the panel
  1637. // already references in its own configuration (an inbound's TLS
  1638. // certificateFile or the panel's own web cert). The path handed to
  1639. // os.ReadFile comes from that allow-list, never directly from the
  1640. // caller-supplied value.
  1641. known, ok := s.resolveKnownCertFile(path)
  1642. if !ok {
  1643. return nil, common.NewError("certificate file is not referenced by any inbound or panel setting")
  1644. }
  1645. b, err := os.ReadFile(known)
  1646. if err != nil {
  1647. return nil, err
  1648. }
  1649. certBytes = b
  1650. } else if strings.TrimSpace(certContent) != "" {
  1651. certBytes = []byte(certContent)
  1652. } else {
  1653. return nil, common.NewError("no certificate provided")
  1654. }
  1655. var certs []*x509.Certificate
  1656. if bytes.Contains(certBytes, []byte("BEGIN")) {
  1657. rest := certBytes
  1658. for {
  1659. block, remain := pem.Decode(rest)
  1660. if block == nil {
  1661. break
  1662. }
  1663. cert, err := x509.ParseCertificate(block.Bytes)
  1664. if err != nil {
  1665. return nil, common.NewError("unable to decode certificate: ", err)
  1666. }
  1667. certs = append(certs, cert)
  1668. rest = remain
  1669. }
  1670. } else {
  1671. parsed, err := x509.ParseCertificates(certBytes)
  1672. if err != nil {
  1673. return nil, common.NewError("unable to parse certificates: ", err)
  1674. }
  1675. certs = parsed
  1676. }
  1677. if len(certs) == 0 {
  1678. return nil, common.NewError("no certificates found")
  1679. }
  1680. hashes := make([]string, 0, len(certs))
  1681. for _, cert := range certs {
  1682. sum := sha256.Sum256(cert.Raw)
  1683. hashes = append(hashes, hex.EncodeToString(sum[:]))
  1684. }
  1685. return hashes, nil
  1686. }
  1687. // resolveKnownCertFile checks the caller-supplied certificate path against the
  1688. // set of certificate files the panel already references (inbound TLS configs
  1689. // plus the panel's own web cert) and, on a match, returns the path taken from
  1690. // that configuration — not the caller's value. This both confines reads to
  1691. // known certificates and breaks the user-input-to-filesystem taint flow.
  1692. func (s *ServerService) resolveKnownCertFile(certFile string) (string, bool) {
  1693. want := filepath.Clean(certFile)
  1694. for _, known := range s.knownCertFiles() {
  1695. if filepath.Clean(known) == want {
  1696. return known, true
  1697. }
  1698. }
  1699. return "", false
  1700. }
  1701. // knownCertFiles collects every certificate file path the panel legitimately
  1702. // references: the certificateFile of each inbound's TLS settings and the
  1703. // panel's own web TLS certificate.
  1704. func (s *ServerService) knownCertFiles() []string {
  1705. var files []string
  1706. if cert, err := s.settingService.GetCertFile(); err == nil {
  1707. if cert = strings.TrimSpace(cert); cert != "" {
  1708. files = append(files, cert)
  1709. }
  1710. }
  1711. if inbounds, err := s.inboundService.GetAllInbounds(); err == nil {
  1712. for _, inbound := range inbounds {
  1713. files = collectCertFiles(inbound.StreamSettings, files)
  1714. }
  1715. }
  1716. return files
  1717. }
  1718. // collectCertFiles walks a stream-settings JSON document and appends the value
  1719. // of every "certificateFile" field it finds (TLS settings may nest them under
  1720. // several keys depending on the security type).
  1721. func collectCertFiles(streamSettings string, out []string) []string {
  1722. streamSettings = strings.TrimSpace(streamSettings)
  1723. if streamSettings == "" {
  1724. return out
  1725. }
  1726. var parsed any
  1727. if err := json.Unmarshal([]byte(streamSettings), &parsed); err != nil {
  1728. return out
  1729. }
  1730. return walkCertFiles(parsed, out)
  1731. }
  1732. func walkCertFiles(node any, out []string) []string {
  1733. switch v := node.(type) {
  1734. case map[string]any:
  1735. for key, val := range v {
  1736. if key == "certificateFile" {
  1737. if path, ok := val.(string); ok {
  1738. if path = strings.TrimSpace(path); path != "" {
  1739. out = append(out, path)
  1740. }
  1741. }
  1742. }
  1743. out = walkCertFiles(val, out)
  1744. }
  1745. case []any:
  1746. for _, item := range v {
  1747. out = walkCertFiles(item, out)
  1748. }
  1749. }
  1750. return out
  1751. }
  1752. // GetRemoteCertHash opens a uTLS (Chrome fingerprint) handshake to a remote
  1753. // endpoint and returns the hex-encoded SHA-256 of its leaf certificate — the
  1754. // value to put in pinnedPeerCertSha256 (pcs) when pinning a server whose
  1755. // certificate file you don't hold (a CDN front, a REALITY dest, an external
  1756. // proxy). A native handshake replaces the old `xray tls ping` subprocess so the
  1757. // real dial/handshake failure (connection refused, timeout, …) surfaces
  1758. // verbatim. `server` may be host or host:port; the port defaults to 443.
  1759. func (s *ServerService) GetRemoteCertHash(server string) ([]string, error) {
  1760. server = strings.TrimSpace(server)
  1761. if server == "" {
  1762. return nil, common.NewError("no server provided")
  1763. }
  1764. host, port := server, "443"
  1765. if h, p, err := stdnet.SplitHostPort(server); err == nil {
  1766. host, port = h, p
  1767. }
  1768. dialer := stdnet.Dialer{Timeout: 10 * time.Second}
  1769. tcpConn, err := dialer.Dial("tcp", stdnet.JoinHostPort(host, port))
  1770. if err != nil {
  1771. return nil, common.NewErrorf("failed to dial %s: %s", stdnet.JoinHostPort(host, port), err)
  1772. }
  1773. defer tcpConn.Close()
  1774. _ = tcpConn.SetDeadline(time.Now().Add(15 * time.Second))
  1775. tlsConn := utls.UClient(tcpConn, &utls.Config{
  1776. ServerName: host,
  1777. InsecureSkipVerify: true,
  1778. NextProtos: []string{"h2", "http/1.1"},
  1779. }, utls.HelloChrome_Auto)
  1780. defer tlsConn.Close()
  1781. if err := tlsConn.Handshake(); err != nil {
  1782. return nil, common.NewErrorf("tls handshake with %s failed: %s", host, err)
  1783. }
  1784. certs := tlsConn.ConnectionState().PeerCertificates
  1785. if len(certs) == 0 {
  1786. return nil, common.NewError("no certificate returned by ", host)
  1787. }
  1788. // PeerCertificates[0] is always the leaf the connection verifies against —
  1789. // robust for IP-only self-signed certs that carry no DNS SANs.
  1790. sum := sha256.Sum256(certs[0].Raw)
  1791. return []string{hex.EncodeToString(sum[:])}, nil
  1792. }
  1793. func (s *ServerService) GetNewEchCert(sni string) (any, error) {
  1794. // Run the command
  1795. cmd := exec.Command(xray.GetBinaryPath(), "tls", "ech", "--serverName", sni)
  1796. var out bytes.Buffer
  1797. cmd.Stdout = &out
  1798. err := cmd.Run()
  1799. if err != nil {
  1800. return nil, err
  1801. }
  1802. lines := strings.Split(out.String(), "\n")
  1803. if len(lines) < 4 {
  1804. return nil, common.NewError("invalid ech cert")
  1805. }
  1806. configList := lines[1]
  1807. serverKeys := lines[3]
  1808. return map[string]any{
  1809. "echServerKeys": serverKeys,
  1810. "echConfigList": configList,
  1811. }, nil
  1812. }
  1813. func (s *ServerService) GetNewVlessEnc() (any, error) {
  1814. cmd := exec.Command(xray.GetBinaryPath(), "vlessenc")
  1815. var out bytes.Buffer
  1816. cmd.Stdout = &out
  1817. if err := cmd.Run(); err != nil {
  1818. return nil, err
  1819. }
  1820. return map[string]any{
  1821. "auths": parseVlessEncAuths(out.String()),
  1822. }, nil
  1823. }
  1824. func parseVlessEncAuths(output string) []map[string]string {
  1825. lines := strings.Split(output, "\n")
  1826. var auths []map[string]string
  1827. var current map[string]string
  1828. for _, line := range lines {
  1829. line = strings.TrimSpace(line)
  1830. if strings.HasPrefix(line, "Authentication:") {
  1831. if current != nil {
  1832. auths = append(auths, current)
  1833. }
  1834. label := strings.TrimSpace(strings.TrimPrefix(line, "Authentication:"))
  1835. current = map[string]string{
  1836. "id": vlessEncAuthID(label),
  1837. "label": label,
  1838. }
  1839. } else if strings.HasPrefix(line, `"decryption"`) || strings.HasPrefix(line, `"encryption"`) {
  1840. parts := strings.SplitN(line, ":", 2)
  1841. if len(parts) == 2 && current != nil {
  1842. key := strings.Trim(parts[0], `" `)
  1843. val := strings.TrimSpace(parts[1])
  1844. val = strings.TrimSuffix(val, ",")
  1845. val = strings.Trim(val, `" `)
  1846. current[key] = val
  1847. }
  1848. }
  1849. }
  1850. if current != nil {
  1851. auths = append(auths, current)
  1852. }
  1853. return auths
  1854. }
  1855. func vlessEncAuthID(label string) string {
  1856. normalized := strings.NewReplacer("-", "", "_", "", " ", "").Replace(strings.ToLower(label))
  1857. switch {
  1858. case strings.Contains(normalized, "mlkem768"):
  1859. return "mlkem768"
  1860. case strings.Contains(normalized, "x25519"):
  1861. return "x25519"
  1862. default:
  1863. return normalized
  1864. }
  1865. }
  1866. func (s *ServerService) GetNewUUID() (map[string]string, error) {
  1867. newUUID, err := uuid.NewRandom()
  1868. if err != nil {
  1869. return nil, fmt.Errorf("failed to generate UUID: %w", err)
  1870. }
  1871. return map[string]string{
  1872. "uuid": newUUID.String(),
  1873. }, nil
  1874. }
  1875. func (s *ServerService) GetNewmlkem768() (any, error) {
  1876. // Run the command
  1877. cmd := exec.Command(xray.GetBinaryPath(), "mlkem768")
  1878. var out bytes.Buffer
  1879. cmd.Stdout = &out
  1880. err := cmd.Run()
  1881. if err != nil {
  1882. return nil, err
  1883. }
  1884. lines := strings.Split(out.String(), "\n")
  1885. SeedLine := strings.Split(lines[0], ":")
  1886. ClientLine := strings.Split(lines[1], ":")
  1887. seed := strings.TrimSpace(SeedLine[1])
  1888. client := strings.TrimSpace(ClientLine[1])
  1889. keyPair := map[string]any{
  1890. "seed": seed,
  1891. "client": client,
  1892. }
  1893. return keyPair, nil
  1894. }