1
0

server.go 57 KB

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