server.go 61 KB

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