server.go 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139
  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 so a downloaded or Telegram-sent backup identifies the server
  1148. // it came from. requestHost is the browser's address (the getDb handler passes
  1149. // c.Request.Host, matching the host shown in the panel title); it is preferred
  1150. // when present, otherwise the configured web domain and then the server's public
  1151. // IP are used. The extension is .dump on PostgreSQL and .db on SQLite; the base
  1152. // falls back to "x-ui" when no address is known.
  1153. func (s *ServerService) BackupFilename(requestHost string) string {
  1154. ext := ".db"
  1155. if database.IsPostgres() {
  1156. ext = ".dump"
  1157. }
  1158. return s.backupHost(requestHost) + ext
  1159. }
  1160. // backupHost picks the address used to name backup files: the browser's request
  1161. // host (port stripped, the same value the panel title shows) when available,
  1162. // otherwise the configured web domain and then the cached public IP (IPv4 before
  1163. // IPv6), reduced to safe filename characters.
  1164. func (s *ServerService) backupHost(requestHost string) string {
  1165. host := extractHostname(strings.TrimSpace(requestHost))
  1166. if host == "" {
  1167. if domain, err := s.settingService.GetWebDomain(); err == nil {
  1168. host = strings.TrimSpace(domain)
  1169. }
  1170. }
  1171. if host == "" {
  1172. if st := s.LastStatus(); st != nil {
  1173. if ip := st.PublicIP.IPv4; ip != "" && ip != "N/A" {
  1174. host = ip
  1175. } else if ip := st.PublicIP.IPv6; ip != "" && ip != "N/A" {
  1176. host = ip
  1177. }
  1178. }
  1179. }
  1180. return sanitizeBackupHost(host)
  1181. }
  1182. // sanitizeBackupHost reduces a host to characters safe in a download filename
  1183. // (the getDb handler enforces ^[a-zA-Z0-9_\-.]+$). IPv6 brackets are stripped
  1184. // and any other character — such as the colons in an IPv6 address — becomes a
  1185. // hyphen. Returns "x-ui" when nothing usable remains.
  1186. func sanitizeBackupHost(host string) string {
  1187. host = strings.Trim(host, "[]")
  1188. var b strings.Builder
  1189. for _, r := range host {
  1190. switch {
  1191. case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '.', r == '-', r == '_':
  1192. b.WriteRune(r)
  1193. default:
  1194. b.WriteRune('-')
  1195. }
  1196. }
  1197. out := strings.Trim(b.String(), ".-")
  1198. if out == "" {
  1199. return "x-ui"
  1200. }
  1201. return out
  1202. }
  1203. // GetMigration produces a cross-engine migration file plus its filename: on a
  1204. // SQLite panel it returns a portable .dump (SQL text), and on a PostgreSQL panel
  1205. // it returns a .db SQLite database built from the live data. Either output can
  1206. // then seed a panel running on the other backend.
  1207. func (s *ServerService) GetMigration() ([]byte, string, error) {
  1208. if database.IsPostgres() {
  1209. tmp, err := os.CreateTemp("", "x-ui-migration-*.db")
  1210. if err != nil {
  1211. return nil, "", err
  1212. }
  1213. tmpPath := tmp.Name()
  1214. tmp.Close()
  1215. defer os.Remove(tmpPath)
  1216. if err := database.ExportPostgresToSQLite(config.GetDBDSN(), tmpPath); err != nil {
  1217. return nil, "", err
  1218. }
  1219. data, err := os.ReadFile(tmpPath)
  1220. if err != nil {
  1221. return nil, "", err
  1222. }
  1223. return data, "x-ui.db", nil
  1224. }
  1225. // SQLite panel: checkpoint so the .db reflects the latest writes, then dump.
  1226. if err := database.Checkpoint(); err != nil {
  1227. return nil, "", err
  1228. }
  1229. data, err := database.DumpSQLiteToBytes(config.GetDBPath())
  1230. if err != nil {
  1231. return nil, "", err
  1232. }
  1233. return data, "x-ui.dump", nil
  1234. }
  1235. func (s *ServerService) ImportDB(file multipart.File) error {
  1236. if database.IsPostgres() {
  1237. return s.importPostgresDB(file)
  1238. }
  1239. // Check if the file is a SQLite database
  1240. isValidDb, err := database.IsSQLiteDB(file)
  1241. if err != nil {
  1242. return common.NewErrorf("Error checking db file format: %v", err)
  1243. }
  1244. if !isValidDb {
  1245. return common.NewError("Invalid db file format")
  1246. }
  1247. // Reset the file reader to the beginning
  1248. _, err = file.Seek(0, 0)
  1249. if err != nil {
  1250. return common.NewErrorf("Error resetting file reader: %v", err)
  1251. }
  1252. // Save the file as a temporary file
  1253. tempPath := fmt.Sprintf("%s.temp", config.GetDBPath())
  1254. // Remove the existing temporary file (if any)
  1255. if _, err := os.Stat(tempPath); err == nil {
  1256. if errRemove := os.Remove(tempPath); errRemove != nil {
  1257. return common.NewErrorf("Error removing existing temporary db file: %v", errRemove)
  1258. }
  1259. }
  1260. // Create the temporary file
  1261. tempFile, err := os.Create(tempPath)
  1262. if err != nil {
  1263. return common.NewErrorf("Error creating temporary db file: %v", err)
  1264. }
  1265. // Robust deferred cleanup for the temporary file
  1266. defer func() {
  1267. if tempFile != nil {
  1268. if cerr := tempFile.Close(); cerr != nil {
  1269. logger.Warningf("Warning: failed to close temp file: %v", cerr)
  1270. }
  1271. }
  1272. if _, err := os.Stat(tempPath); err == nil {
  1273. if rerr := os.Remove(tempPath); rerr != nil {
  1274. logger.Warningf("Warning: failed to remove temp file: %v", rerr)
  1275. }
  1276. }
  1277. }()
  1278. // Save uploaded file to temporary file
  1279. if _, err = io.Copy(tempFile, file); err != nil {
  1280. return common.NewErrorf("Error saving db: %v", err)
  1281. }
  1282. // Close temp file before opening via sqlite
  1283. if err = tempFile.Close(); err != nil {
  1284. return common.NewErrorf("Error closing temporary db file: %v", err)
  1285. }
  1286. tempFile = nil
  1287. // Validate integrity (no migrations / side effects)
  1288. if err = database.ValidateSQLiteDB(tempPath); err != nil {
  1289. return common.NewErrorf("Invalid or corrupt db file: %v", err)
  1290. }
  1291. xrayStopped := true
  1292. defer func() {
  1293. if xrayStopped {
  1294. if errR := s.RestartXrayService(); errR != nil {
  1295. logger.Warningf("Failed to restart Xray after DB import error: %v", errR)
  1296. }
  1297. }
  1298. }()
  1299. if errStop := s.StopXrayService(); errStop != nil {
  1300. logger.Warningf("Failed to stop Xray before DB import: %v", errStop)
  1301. }
  1302. if errClose := database.CloseDB(); errClose != nil {
  1303. logger.Warningf("Failed to close existing DB before replacement: %v", errClose)
  1304. }
  1305. // Backup the current database for fallback
  1306. fallbackPath := fmt.Sprintf("%s.backup", config.GetDBPath())
  1307. // Remove the existing fallback file (if any)
  1308. if _, err := os.Stat(fallbackPath); err == nil {
  1309. if errRemove := os.Remove(fallbackPath); errRemove != nil {
  1310. return common.NewErrorf("Error removing existing fallback db file: %v", errRemove)
  1311. }
  1312. }
  1313. // Move the current database to the fallback location
  1314. if err = os.Rename(config.GetDBPath(), fallbackPath); err != nil {
  1315. return common.NewErrorf("Error backing up current db file: %v", err)
  1316. }
  1317. // Defer fallback cleanup ONLY if everything goes well
  1318. defer func() {
  1319. if _, err := os.Stat(fallbackPath); err == nil {
  1320. if rerr := os.Remove(fallbackPath); rerr != nil {
  1321. logger.Warningf("Warning: failed to remove fallback file: %v", rerr)
  1322. }
  1323. }
  1324. }()
  1325. // Move temp to DB path
  1326. if err = os.Rename(tempPath, config.GetDBPath()); err != nil {
  1327. // Restore from fallback
  1328. if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
  1329. return common.NewErrorf("Error moving db file and restoring fallback: %v", errRename)
  1330. }
  1331. return common.NewErrorf("Error moving db file: %v", err)
  1332. }
  1333. // Open & migrate new DB
  1334. if err = database.InitDB(config.GetDBPath()); err != nil {
  1335. if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
  1336. return common.NewErrorf("Error migrating db and restoring fallback: %v", errRename)
  1337. }
  1338. return common.NewErrorf("Error migrating db: %v", err)
  1339. }
  1340. s.inboundService.MigrateDB()
  1341. xrayStopped = false
  1342. if err = s.RestartXrayService(); err != nil {
  1343. return common.NewErrorf("Imported DB but failed to start Xray: %v", err)
  1344. }
  1345. return nil
  1346. }
  1347. // pgConnEnv turns the configured PostgreSQL DSN into the PG* environment used by
  1348. // pg_dump/pg_restore, keeping the password out of the process argument list.
  1349. func pgConnEnv(dsn string) (env []string, dbname string, err error) {
  1350. u, err := url.Parse(strings.TrimSpace(dsn))
  1351. if err != nil {
  1352. return nil, "", err
  1353. }
  1354. if u.Scheme != "postgres" && u.Scheme != "postgresql" {
  1355. return nil, "", common.NewErrorf("unsupported DSN scheme %q", u.Scheme)
  1356. }
  1357. dbname = strings.TrimPrefix(u.Path, "/")
  1358. if dbname == "" {
  1359. return nil, "", common.NewError("PostgreSQL DSN is missing a database name")
  1360. }
  1361. host := u.Hostname()
  1362. if host == "" {
  1363. host = "127.0.0.1"
  1364. }
  1365. port := u.Port()
  1366. if port == "" {
  1367. port = "5432"
  1368. }
  1369. env = append(os.Environ(), "PGHOST="+host, "PGPORT="+port, "PGDATABASE="+dbname)
  1370. if user := u.User.Username(); user != "" {
  1371. env = append(env, "PGUSER="+user)
  1372. }
  1373. if pass, ok := u.User.Password(); ok {
  1374. env = append(env, "PGPASSWORD="+pass)
  1375. }
  1376. if sslmode := u.Query().Get("sslmode"); sslmode != "" {
  1377. env = append(env, "PGSSLMODE="+sslmode)
  1378. }
  1379. return env, dbname, nil
  1380. }
  1381. func (s *ServerService) exportPostgresDB() ([]byte, error) {
  1382. bin, err := exec.LookPath("pg_dump")
  1383. if err != nil {
  1384. return nil, common.NewError("pg_dump not found on the server; install the postgresql-client package to back up a PostgreSQL database")
  1385. }
  1386. env, dbname, err := pgConnEnv(config.GetDBDSN())
  1387. if err != nil {
  1388. return nil, common.NewErrorf("invalid PostgreSQL DSN: %v", err)
  1389. }
  1390. cmd := exec.Command(bin, "--format=custom", "--no-owner", "--no-privileges", "--dbname", dbname)
  1391. cmd.Env = env
  1392. var out, stderr bytes.Buffer
  1393. cmd.Stdout = &out
  1394. cmd.Stderr = &stderr
  1395. if err := cmd.Run(); err != nil {
  1396. return nil, common.NewErrorf("pg_dump failed: %v: %s", err, strings.TrimSpace(stderr.String()))
  1397. }
  1398. return out.Bytes(), nil
  1399. }
  1400. func (s *ServerService) importPostgresDB(file multipart.File) error {
  1401. header := make([]byte, 5)
  1402. if _, err := file.ReadAt(header, 0); err != nil {
  1403. return common.NewErrorf("Error reading dump file: %v", err)
  1404. }
  1405. if string(header) != "PGDMP" {
  1406. return common.NewError("Invalid file: expected a PostgreSQL custom-format dump (.dump) created by this panel's Back Up")
  1407. }
  1408. if _, err := file.Seek(0, 0); err != nil {
  1409. return common.NewErrorf("Error resetting file reader: %v", err)
  1410. }
  1411. bin, err := exec.LookPath("pg_restore")
  1412. if err != nil {
  1413. return common.NewError("pg_restore not found on the server; install the postgresql-client package to restore a PostgreSQL database")
  1414. }
  1415. env, dbname, err := pgConnEnv(config.GetDBDSN())
  1416. if err != nil {
  1417. return common.NewErrorf("invalid PostgreSQL DSN: %v", err)
  1418. }
  1419. tempFile, err := os.CreateTemp("", "x-ui-pg-restore-*.dump")
  1420. if err != nil {
  1421. return common.NewErrorf("Error creating temporary dump file: %v", err)
  1422. }
  1423. tempPath := tempFile.Name()
  1424. defer os.Remove(tempPath)
  1425. if _, err := io.Copy(tempFile, file); err != nil {
  1426. tempFile.Close()
  1427. return common.NewErrorf("Error saving dump: %v", err)
  1428. }
  1429. if err := tempFile.Close(); err != nil {
  1430. return common.NewErrorf("Error closing temporary dump file: %v", err)
  1431. }
  1432. xrayStopped := true
  1433. defer func() {
  1434. if xrayStopped {
  1435. if errR := s.RestartXrayService(); errR != nil {
  1436. logger.Warningf("Failed to restart Xray after DB restore error: %v", errR)
  1437. }
  1438. }
  1439. }()
  1440. if errStop := s.StopXrayService(); errStop != nil {
  1441. logger.Warningf("Failed to stop Xray before DB restore: %v", errStop)
  1442. }
  1443. if errClose := database.CloseDB(); errClose != nil {
  1444. logger.Warningf("Failed to close existing DB before restore: %v", errClose)
  1445. }
  1446. cmd := exec.Command(bin,
  1447. "--clean", "--if-exists", "--no-owner", "--no-privileges",
  1448. "--single-transaction", "--dbname", dbname, tempPath,
  1449. )
  1450. cmd.Env = env
  1451. var stderr bytes.Buffer
  1452. cmd.Stderr = &stderr
  1453. runErr := cmd.Run()
  1454. if errInit := database.InitDB(config.GetDBPath()); errInit != nil {
  1455. return common.NewErrorf("Restore finished but reopening the database failed: %v", errInit)
  1456. }
  1457. s.inboundService.MigrateDB()
  1458. if runErr != nil {
  1459. return common.NewErrorf("pg_restore failed (database left unchanged): %v: %s", runErr, strings.TrimSpace(stderr.String()))
  1460. }
  1461. xrayStopped = false
  1462. if err := s.RestartXrayService(); err != nil {
  1463. return common.NewErrorf("Restored DB but failed to start Xray: %v", err)
  1464. }
  1465. return nil
  1466. }
  1467. // IsValidGeofileName validates that the filename is safe for geofile operations.
  1468. // It checks for path traversal attempts and ensures the filename contains only safe characters.
  1469. func (s *ServerService) IsValidGeofileName(filename string) bool {
  1470. if filename == "" {
  1471. return false
  1472. }
  1473. // Check for path traversal attempts
  1474. if strings.Contains(filename, "..") {
  1475. return false
  1476. }
  1477. // Check for path separators (both forward and backward slash)
  1478. if strings.ContainsAny(filename, `/\`) {
  1479. return false
  1480. }
  1481. // Check for absolute path indicators
  1482. if filepath.IsAbs(filename) {
  1483. return false
  1484. }
  1485. // Additional security: only allow alphanumeric, dots, underscores, and hyphens
  1486. // This is stricter than the general filename regex
  1487. validGeofilePattern := `^[a-zA-Z0-9._-]+\.dat$`
  1488. matched, _ := regexp.MatchString(validGeofilePattern, filename)
  1489. return matched
  1490. }
  1491. func (s *ServerService) UpdateGeofile(fileName string) error {
  1492. type geofileEntry struct {
  1493. URL string
  1494. FileName string
  1495. }
  1496. geofileAllowlist := map[string]geofileEntry{
  1497. "geoip.dat": {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip.dat"},
  1498. "geosite.dat": {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite.dat"},
  1499. "geoip_IR.dat": {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geoip.dat", "geoip_IR.dat"},
  1500. "geosite_IR.dat": {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat", "geosite_IR.dat"},
  1501. "geoip_RU.dat": {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip_RU.dat"},
  1502. "geosite_RU.dat": {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite_RU.dat"},
  1503. }
  1504. // Strict allowlist check to avoid writing uncontrolled files
  1505. if fileName != "" {
  1506. if _, ok := geofileAllowlist[fileName]; !ok {
  1507. return common.NewErrorf("Invalid geofile name: %q not in allowlist", fileName)
  1508. }
  1509. }
  1510. client := s.settingService.NewProxiedHTTPClient(0)
  1511. downloadFile := func(url, destPath string) error {
  1512. var req *http.Request
  1513. req, err := http.NewRequest("GET", url, nil)
  1514. if err != nil {
  1515. return common.NewErrorf("Failed to create HTTP request for %s: %v", url, err)
  1516. }
  1517. var localFileModTime time.Time
  1518. if fileInfo, err := os.Stat(destPath); err == nil {
  1519. localFileModTime = fileInfo.ModTime()
  1520. if !localFileModTime.IsZero() {
  1521. req.Header.Set("If-Modified-Since", localFileModTime.UTC().Format(http.TimeFormat))
  1522. }
  1523. }
  1524. resp, err := client.Do(req)
  1525. if err != nil {
  1526. return common.NewErrorf("Failed to download Geofile from %s: %v", url, err)
  1527. }
  1528. defer resp.Body.Close()
  1529. // Parse Last-Modified header from server
  1530. var serverModTime time.Time
  1531. serverModTimeStr := resp.Header.Get("Last-Modified")
  1532. if serverModTimeStr != "" {
  1533. parsedTime, err := time.Parse(http.TimeFormat, serverModTimeStr)
  1534. if err != nil {
  1535. logger.Warningf("Failed to parse Last-Modified header for %s: %v", url, err)
  1536. } else {
  1537. serverModTime = parsedTime
  1538. }
  1539. }
  1540. // Function to update local file's modification time
  1541. updateFileModTime := func() {
  1542. if !serverModTime.IsZero() {
  1543. if err := os.Chtimes(destPath, serverModTime, serverModTime); err != nil {
  1544. logger.Warningf("Failed to update modification time for %s: %v", destPath, err)
  1545. }
  1546. }
  1547. }
  1548. // Handle 304 Not Modified
  1549. if resp.StatusCode == http.StatusNotModified {
  1550. updateFileModTime()
  1551. return nil
  1552. }
  1553. if resp.StatusCode != http.StatusOK {
  1554. return common.NewErrorf("Failed to download Geofile from %s: received status code %d", url, resp.StatusCode)
  1555. }
  1556. file, err := os.Create(destPath)
  1557. if err != nil {
  1558. return common.NewErrorf("Failed to create Geofile %s: %v", destPath, err)
  1559. }
  1560. defer file.Close()
  1561. _, err = io.Copy(file, resp.Body)
  1562. if err != nil {
  1563. return common.NewErrorf("Failed to save Geofile %s: %v", destPath, err)
  1564. }
  1565. updateFileModTime()
  1566. return nil
  1567. }
  1568. var errorMessages []string
  1569. if fileName == "" {
  1570. // Download all geofiles
  1571. for _, entry := range geofileAllowlist {
  1572. destPath := filepath.Join(config.GetBinFolderPath(), entry.FileName)
  1573. if err := downloadFile(entry.URL, destPath); err != nil {
  1574. errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", entry.FileName, err))
  1575. }
  1576. }
  1577. } else {
  1578. entry := geofileAllowlist[fileName]
  1579. destPath := filepath.Join(config.GetBinFolderPath(), entry.FileName)
  1580. if err := downloadFile(entry.URL, destPath); err != nil {
  1581. errorMessages = append(errorMessages, fmt.Sprintf("Error downloading Geofile '%s': %v", entry.FileName, err))
  1582. }
  1583. }
  1584. err := s.RestartXrayService()
  1585. if err != nil {
  1586. errorMessages = append(errorMessages, fmt.Sprintf("Updated Geofile '%s' but Failed to start Xray: %v", fileName, err))
  1587. }
  1588. if len(errorMessages) > 0 {
  1589. return common.NewErrorf("%s", strings.Join(errorMessages, "\r\n"))
  1590. }
  1591. return nil
  1592. }
  1593. func (s *ServerService) GetNewX25519Cert() (any, error) {
  1594. // Run the command
  1595. cmd := exec.Command(xray.GetBinaryPath(), "x25519")
  1596. var out bytes.Buffer
  1597. cmd.Stdout = &out
  1598. err := cmd.Run()
  1599. if err != nil {
  1600. return nil, err
  1601. }
  1602. lines := strings.Split(out.String(), "\n")
  1603. privateKeyLine := strings.Split(lines[0], ":")
  1604. publicKeyLine := strings.Split(lines[1], ":")
  1605. privateKey := strings.TrimSpace(privateKeyLine[1])
  1606. publicKey := strings.TrimSpace(publicKeyLine[1])
  1607. keyPair := map[string]any{
  1608. "privateKey": privateKey,
  1609. "publicKey": publicKey,
  1610. }
  1611. return keyPair, nil
  1612. }
  1613. func (s *ServerService) GetNewmldsa65() (any, error) {
  1614. // Run the command
  1615. cmd := exec.Command(xray.GetBinaryPath(), "mldsa65")
  1616. var out bytes.Buffer
  1617. cmd.Stdout = &out
  1618. err := cmd.Run()
  1619. if err != nil {
  1620. return nil, err
  1621. }
  1622. lines := strings.Split(out.String(), "\n")
  1623. SeedLine := strings.Split(lines[0], ":")
  1624. VerifyLine := strings.Split(lines[1], ":")
  1625. seed := strings.TrimSpace(SeedLine[1])
  1626. verify := strings.TrimSpace(VerifyLine[1])
  1627. keyPair := map[string]any{
  1628. "seed": seed,
  1629. "verify": verify,
  1630. }
  1631. return keyPair, nil
  1632. }
  1633. // GetCertHash parses a certificate (from a file path or inline PEM/DER content)
  1634. // and returns the hex-encoded SHA-256 over each certificate's raw DER — the
  1635. // value xray-core's pinnedPeerCertSha256 (pcs) expects. Lets the panel fill the
  1636. // pinned-cert field from the inbound's own certificate without the user
  1637. // computing the hash by hand.
  1638. func (s *ServerService) GetCertHash(certFile string, certContent string) ([]string, error) {
  1639. var certBytes []byte
  1640. if path := strings.TrimSpace(certFile); path != "" {
  1641. // Guard against path traversal: only hash certificate files the panel
  1642. // already references in its own configuration (an inbound's TLS
  1643. // certificateFile or the panel's own web cert). The path handed to
  1644. // os.ReadFile comes from that allow-list, never directly from the
  1645. // caller-supplied value.
  1646. known, ok := s.resolveKnownCertFile(path)
  1647. if !ok {
  1648. return nil, common.NewError("certificate file is not referenced by any inbound or panel setting")
  1649. }
  1650. b, err := os.ReadFile(known)
  1651. if err != nil {
  1652. return nil, err
  1653. }
  1654. certBytes = b
  1655. } else if strings.TrimSpace(certContent) != "" {
  1656. certBytes = []byte(certContent)
  1657. } else {
  1658. return nil, common.NewError("no certificate provided")
  1659. }
  1660. var certs []*x509.Certificate
  1661. if bytes.Contains(certBytes, []byte("BEGIN")) {
  1662. rest := certBytes
  1663. for {
  1664. block, remain := pem.Decode(rest)
  1665. if block == nil {
  1666. break
  1667. }
  1668. cert, err := x509.ParseCertificate(block.Bytes)
  1669. if err != nil {
  1670. return nil, common.NewError("unable to decode certificate: ", err)
  1671. }
  1672. certs = append(certs, cert)
  1673. rest = remain
  1674. }
  1675. } else {
  1676. parsed, err := x509.ParseCertificates(certBytes)
  1677. if err != nil {
  1678. return nil, common.NewError("unable to parse certificates: ", err)
  1679. }
  1680. certs = parsed
  1681. }
  1682. if len(certs) == 0 {
  1683. return nil, common.NewError("no certificates found")
  1684. }
  1685. hashes := make([]string, 0, len(certs))
  1686. for _, cert := range certs {
  1687. sum := sha256.Sum256(cert.Raw)
  1688. hashes = append(hashes, hex.EncodeToString(sum[:]))
  1689. }
  1690. return hashes, nil
  1691. }
  1692. // resolveKnownCertFile checks the caller-supplied certificate path against the
  1693. // set of certificate files the panel already references (inbound TLS configs
  1694. // plus the panel's own web cert) and, on a match, returns the path taken from
  1695. // that configuration — not the caller's value. This both confines reads to
  1696. // known certificates and breaks the user-input-to-filesystem taint flow.
  1697. func (s *ServerService) resolveKnownCertFile(certFile string) (string, bool) {
  1698. want := filepath.Clean(certFile)
  1699. for _, known := range s.knownCertFiles() {
  1700. if filepath.Clean(known) == want {
  1701. return known, true
  1702. }
  1703. }
  1704. return "", false
  1705. }
  1706. // knownCertFiles collects every certificate file path the panel legitimately
  1707. // references: the certificateFile of each inbound's TLS settings and the
  1708. // panel's own web TLS certificate.
  1709. func (s *ServerService) knownCertFiles() []string {
  1710. var files []string
  1711. if cert, err := s.settingService.GetCertFile(); err == nil {
  1712. if cert = strings.TrimSpace(cert); cert != "" {
  1713. files = append(files, cert)
  1714. }
  1715. }
  1716. if inbounds, err := s.inboundService.GetAllInbounds(); err == nil {
  1717. for _, inbound := range inbounds {
  1718. files = collectCertFiles(inbound.StreamSettings, files)
  1719. }
  1720. }
  1721. return files
  1722. }
  1723. // collectCertFiles walks a stream-settings JSON document and appends the value
  1724. // of every "certificateFile" field it finds (TLS settings may nest them under
  1725. // several keys depending on the security type).
  1726. func collectCertFiles(streamSettings string, out []string) []string {
  1727. streamSettings = strings.TrimSpace(streamSettings)
  1728. if streamSettings == "" {
  1729. return out
  1730. }
  1731. var parsed any
  1732. if err := json.Unmarshal([]byte(streamSettings), &parsed); err != nil {
  1733. return out
  1734. }
  1735. return walkCertFiles(parsed, out)
  1736. }
  1737. func walkCertFiles(node any, out []string) []string {
  1738. switch v := node.(type) {
  1739. case map[string]any:
  1740. for key, val := range v {
  1741. if key == "certificateFile" {
  1742. if path, ok := val.(string); ok {
  1743. if path = strings.TrimSpace(path); path != "" {
  1744. out = append(out, path)
  1745. }
  1746. }
  1747. }
  1748. out = walkCertFiles(val, out)
  1749. }
  1750. case []any:
  1751. for _, item := range v {
  1752. out = walkCertFiles(item, out)
  1753. }
  1754. }
  1755. return out
  1756. }
  1757. // GetRemoteCertHash opens a uTLS (Chrome fingerprint) handshake to a remote
  1758. // endpoint and returns the hex-encoded SHA-256 of its leaf certificate — the
  1759. // value to put in pinnedPeerCertSha256 (pcs) when pinning a server whose
  1760. // certificate file you don't hold (a CDN front, a REALITY dest, an external
  1761. // proxy). A native handshake replaces the old `xray tls ping` subprocess so the
  1762. // real dial/handshake failure (connection refused, timeout, …) surfaces
  1763. // verbatim. `server` may be host or host:port; the port defaults to 443.
  1764. func (s *ServerService) GetRemoteCertHash(server string) ([]string, error) {
  1765. server = strings.TrimSpace(server)
  1766. if server == "" {
  1767. return nil, common.NewError("no server provided")
  1768. }
  1769. host, port := server, "443"
  1770. if h, p, err := stdnet.SplitHostPort(server); err == nil {
  1771. host, port = h, p
  1772. }
  1773. dialer := stdnet.Dialer{Timeout: 10 * time.Second}
  1774. tcpConn, err := dialer.Dial("tcp", stdnet.JoinHostPort(host, port))
  1775. if err != nil {
  1776. return nil, common.NewErrorf("failed to dial %s: %s", stdnet.JoinHostPort(host, port), err)
  1777. }
  1778. defer tcpConn.Close()
  1779. _ = tcpConn.SetDeadline(time.Now().Add(15 * time.Second))
  1780. tlsConn := utls.UClient(tcpConn, &utls.Config{
  1781. ServerName: host,
  1782. InsecureSkipVerify: true,
  1783. NextProtos: []string{"h2", "http/1.1"},
  1784. }, utls.HelloChrome_Auto)
  1785. defer tlsConn.Close()
  1786. if err := tlsConn.Handshake(); err != nil {
  1787. return nil, common.NewErrorf("tls handshake with %s failed: %s", host, err)
  1788. }
  1789. certs := tlsConn.ConnectionState().PeerCertificates
  1790. if len(certs) == 0 {
  1791. return nil, common.NewError("no certificate returned by ", host)
  1792. }
  1793. // PeerCertificates[0] is always the leaf the connection verifies against —
  1794. // robust for IP-only self-signed certs that carry no DNS SANs.
  1795. sum := sha256.Sum256(certs[0].Raw)
  1796. return []string{hex.EncodeToString(sum[:])}, nil
  1797. }
  1798. func (s *ServerService) GetNewEchCert(sni string) (any, error) {
  1799. // Run the command
  1800. cmd := exec.Command(xray.GetBinaryPath(), "tls", "ech", "--serverName", sni)
  1801. var out bytes.Buffer
  1802. cmd.Stdout = &out
  1803. err := cmd.Run()
  1804. if err != nil {
  1805. return nil, err
  1806. }
  1807. lines := strings.Split(out.String(), "\n")
  1808. if len(lines) < 4 {
  1809. return nil, common.NewError("invalid ech cert")
  1810. }
  1811. configList := lines[1]
  1812. serverKeys := lines[3]
  1813. return map[string]any{
  1814. "echServerKeys": serverKeys,
  1815. "echConfigList": configList,
  1816. }, nil
  1817. }
  1818. func (s *ServerService) GetNewVlessEnc() (any, error) {
  1819. cmd := exec.Command(xray.GetBinaryPath(), "vlessenc")
  1820. var out bytes.Buffer
  1821. cmd.Stdout = &out
  1822. if err := cmd.Run(); err != nil {
  1823. return nil, err
  1824. }
  1825. return map[string]any{
  1826. "auths": parseVlessEncAuths(out.String()),
  1827. }, nil
  1828. }
  1829. func parseVlessEncAuths(output string) []map[string]string {
  1830. lines := strings.Split(output, "\n")
  1831. var auths []map[string]string
  1832. var current map[string]string
  1833. for _, line := range lines {
  1834. line = strings.TrimSpace(line)
  1835. if strings.HasPrefix(line, "Authentication:") {
  1836. if current != nil {
  1837. auths = append(auths, current)
  1838. }
  1839. label := strings.TrimSpace(strings.TrimPrefix(line, "Authentication:"))
  1840. current = map[string]string{
  1841. "id": vlessEncAuthID(label),
  1842. "label": label,
  1843. }
  1844. } else if strings.HasPrefix(line, `"decryption"`) || strings.HasPrefix(line, `"encryption"`) {
  1845. parts := strings.SplitN(line, ":", 2)
  1846. if len(parts) == 2 && current != nil {
  1847. key := strings.Trim(parts[0], `" `)
  1848. val := strings.TrimSpace(parts[1])
  1849. val = strings.TrimSuffix(val, ",")
  1850. val = strings.Trim(val, `" `)
  1851. current[key] = val
  1852. }
  1853. }
  1854. }
  1855. if current != nil {
  1856. auths = append(auths, current)
  1857. }
  1858. return auths
  1859. }
  1860. func vlessEncAuthID(label string) string {
  1861. normalized := strings.NewReplacer("-", "", "_", "", " ", "").Replace(strings.ToLower(label))
  1862. switch {
  1863. case strings.Contains(normalized, "mlkem768"):
  1864. return "mlkem768"
  1865. case strings.Contains(normalized, "x25519"):
  1866. return "x25519"
  1867. default:
  1868. return normalized
  1869. }
  1870. }
  1871. func (s *ServerService) GetNewUUID() (map[string]string, error) {
  1872. newUUID, err := uuid.NewRandom()
  1873. if err != nil {
  1874. return nil, fmt.Errorf("failed to generate UUID: %w", err)
  1875. }
  1876. return map[string]string{
  1877. "uuid": newUUID.String(),
  1878. }, nil
  1879. }
  1880. func (s *ServerService) GetNewmlkem768() (any, error) {
  1881. // Run the command
  1882. cmd := exec.Command(xray.GetBinaryPath(), "mlkem768")
  1883. var out bytes.Buffer
  1884. cmd.Stdout = &out
  1885. err := cmd.Run()
  1886. if err != nil {
  1887. return nil, err
  1888. }
  1889. lines := strings.Split(out.String(), "\n")
  1890. SeedLine := strings.Split(lines[0], ":")
  1891. ClientLine := strings.Split(lines[1], ":")
  1892. seed := strings.TrimSpace(SeedLine[1])
  1893. client := strings.TrimSpace(ClientLine[1])
  1894. keyPair := map[string]any{
  1895. "seed": seed,
  1896. "client": client,
  1897. }
  1898. return keyPair, nil
  1899. }