config.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. // Package config provides configuration management utilities for the 3x-ui panel,
  2. // including version information, logging levels, database paths, and environment variable handling.
  3. package config
  4. import (
  5. _ "embed"
  6. "fmt"
  7. "io"
  8. "os"
  9. "path/filepath"
  10. "runtime"
  11. "strconv"
  12. "strings"
  13. "testing"
  14. )
  15. //go:embed version
  16. var version string
  17. //go:embed name
  18. var name string
  19. // buildCommit and buildDate are injected at build time via `-ldflags -X` for
  20. // CI per-commit (dev channel) builds; see .github/workflows/release.yml. They
  21. // stay empty for a plain `go build` and for stable tagged releases, which is how
  22. // IsDevBuild tells a rolling dev build apart from a stable/local one.
  23. var (
  24. buildCommit string
  25. buildDate string
  26. )
  27. // LogLevel represents the logging level for the application.
  28. type LogLevel string
  29. // Logging level constants
  30. const (
  31. Debug LogLevel = "debug"
  32. Info LogLevel = "info"
  33. Notice LogLevel = "notice"
  34. Warning LogLevel = "warning"
  35. Error LogLevel = "error"
  36. )
  37. // GetBaseVersion returns the raw embedded release version of the 3x-ui panel
  38. // (e.g. "3.4.0"). This is the panel's own version, not the Xray version. For the
  39. // version a panel advertises/displays (which adds a "dev+<sha>" label on dev
  40. // builds), use GetPanelVersion.
  41. func GetBaseVersion() string {
  42. return strings.TrimSpace(version)
  43. }
  44. // GetName returns the name of the 3x-ui application.
  45. func GetName() string {
  46. return strings.TrimSpace(name)
  47. }
  48. // GetBuildCommit returns the short git commit this binary was built from, or an
  49. // empty string for a plain/local build or a stable tagged release.
  50. func GetBuildCommit() string {
  51. return strings.TrimSpace(buildCommit)
  52. }
  53. // GetBuildDate returns the UTC build timestamp injected at build time, or empty.
  54. func GetBuildDate() string {
  55. return strings.TrimSpace(buildDate)
  56. }
  57. // IsDevBuild reports whether this binary is a CI per-commit (dev channel) build,
  58. // detected by the injected commit. Stable releases and local builds return false.
  59. func IsDevBuild() bool {
  60. return GetBuildCommit() != ""
  61. }
  62. // GetPanelVersion returns the version a panel advertises to a managing master
  63. // node and displays in the UI: the plain version for stable builds, or
  64. // "dev+<short commit>" for dev builds. The dev form mirrors the master's
  65. // getPanelUpdateInfo latestVersion so a node on the current dev commit compares
  66. // as up to date instead of always showing "update available".
  67. func GetPanelVersion() string {
  68. if !IsDevBuild() {
  69. return GetBaseVersion()
  70. }
  71. commit := GetBuildCommit()
  72. if len(commit) > 8 {
  73. commit = commit[:8]
  74. }
  75. return "dev+" + commit
  76. }
  77. // GetLogLevel returns the current logging level based on environment variables or defaults to Info.
  78. func GetLogLevel() LogLevel {
  79. if IsDebug() {
  80. return Debug
  81. }
  82. logLevel := os.Getenv("XUI_LOG_LEVEL")
  83. if logLevel == "" {
  84. return Info
  85. }
  86. return LogLevel(logLevel)
  87. }
  88. // IsDebug returns true if debug mode is enabled via the XUI_DEBUG environment variable.
  89. func IsDebug() bool {
  90. return os.Getenv("XUI_DEBUG") == "true"
  91. }
  92. // IsSkipHSTS returns true if skipping HSTS mode is enabled via the XUI_SKIP_HSTS environment variable.
  93. func IsSkipHSTS() bool {
  94. return os.Getenv("XUI_SKIP_HSTS") == "true"
  95. }
  96. func GetPortOverride() (port int, configured bool, err error) {
  97. value, ok := os.LookupEnv("XUI_PORT")
  98. if !ok || strings.TrimSpace(value) == "" {
  99. return 0, false, nil
  100. }
  101. port, err = strconv.Atoi(strings.TrimSpace(value))
  102. if err != nil {
  103. return 0, true, fmt.Errorf("parse XUI_PORT: %w", err)
  104. }
  105. if port < 1 || port > 65535 {
  106. return 0, true, fmt.Errorf("XUI_PORT must be between 1 and 65535")
  107. }
  108. return port, true, nil
  109. }
  110. // GetBinFolderPath returns the path to the binary folder, defaulting to "bin" if not set via XUI_BIN_FOLDER.
  111. func GetBinFolderPath() string {
  112. binFolderPath := os.Getenv("XUI_BIN_FOLDER")
  113. if binFolderPath == "" {
  114. binFolderPath = "bin"
  115. }
  116. return binFolderPath
  117. }
  118. func getBaseDir() string {
  119. exePath, err := os.Executable()
  120. if err != nil {
  121. return "."
  122. }
  123. exeDir := filepath.Dir(exePath)
  124. exeDirLower := strings.ToLower(filepath.ToSlash(exeDir))
  125. if strings.Contains(exeDirLower, "/appdata/local/temp/") || strings.Contains(exeDirLower, "/go-build") {
  126. wd, err := os.Getwd()
  127. if err != nil {
  128. return "."
  129. }
  130. return wd
  131. }
  132. return exeDir
  133. }
  134. // GetDBFolderPath returns the path to the database folder based on environment variables or platform defaults.
  135. func GetDBFolderPath() string {
  136. dbFolderPath := os.Getenv("XUI_DB_FOLDER")
  137. if dbFolderPath != "" {
  138. return dbFolderPath
  139. }
  140. if runtime.GOOS == "windows" {
  141. return getBaseDir()
  142. }
  143. return "/etc/x-ui"
  144. }
  145. // GetDBPath returns the full path to the database file.
  146. func GetDBPath() string {
  147. return fmt.Sprintf("%s/%s.db", GetDBFolderPath(), GetName())
  148. }
  149. // GetUpdateStatusFilePath returns the path to the panel self-update status
  150. // file update.sh writes on completion. It lives beside the database, outside
  151. // XUI_MAIN_FOLDER, so it survives an update regardless of what happens to
  152. // that folder.
  153. func GetUpdateStatusFilePath() string {
  154. return filepath.Join(GetDBFolderPath(), "update-status.json")
  155. }
  156. // GetDBKind returns the configured database backend: "sqlite" (default) or "postgres".
  157. func GetDBKind() string {
  158. v := strings.ToLower(strings.TrimSpace(os.Getenv("XUI_DB_TYPE")))
  159. switch v {
  160. case "postgres", "postgresql", "pg":
  161. return "postgres"
  162. default:
  163. return "sqlite"
  164. }
  165. }
  166. // GetDBDSN returns the PostgreSQL DSN from XUI_DB_DSN. Empty for sqlite.
  167. func GetDBDSN() string {
  168. return strings.TrimSpace(os.Getenv("XUI_DB_DSN"))
  169. }
  170. // GetNodeTokenEncryptionMode returns off, migration, or required. Explicit
  171. // policy prevents a missing key from silently downgrading encrypted storage.
  172. func GetNodeTokenEncryptionMode() string {
  173. return strings.TrimSpace(os.Getenv("NODE_TOKEN_ENCRYPTION"))
  174. }
  175. // GetNodeTokenKeyFile returns the mode-0600 keyring path, configurable through
  176. // XUI_NODE_TOKEN_KEY_FILE.
  177. func GetNodeTokenKeyFile() string {
  178. if p := strings.TrimSpace(os.Getenv("XUI_NODE_TOKEN_KEY_FILE")); p != "" {
  179. return p
  180. }
  181. return "/etc/x-ui/node_token_key.json"
  182. }
  183. // GetNodeTokenKeyEnv returns the name of the env var holding a single base64
  184. // 32-byte node-token key (secondary to the key file). Empty value => unused.
  185. func GetNodeTokenKeyEnv() string {
  186. return "XUI_NODE_TOKEN_KEY"
  187. }
  188. // GetEnvFilePaths returns the candidate service environment file paths (the file
  189. // systemd loads via EnvironmentFile) across the supported distro families.
  190. func GetEnvFilePaths() []string {
  191. if runtime.GOOS == "windows" {
  192. return nil
  193. }
  194. return []string{
  195. "/etc/default/x-ui",
  196. "/etc/conf.d/x-ui",
  197. "/etc/sysconfig/x-ui",
  198. }
  199. }
  200. // GetLogFolder returns the path to the log folder based on environment variables or platform defaults.
  201. func GetLogFolder() string {
  202. logFolderPath := os.Getenv("XUI_LOG_FOLDER")
  203. if logFolderPath != "" {
  204. return logFolderPath
  205. }
  206. // Under `go test` the Windows default below is CWD-relative ("./log"), which
  207. // scatters a log/ directory through the source tree (one per tested package).
  208. // Redirect test runs to a shared temp folder so the source tree stays clean.
  209. if testing.Testing() {
  210. return filepath.Join(os.TempDir(), "3x-ui-test-log")
  211. }
  212. if runtime.GOOS == "windows" {
  213. return filepath.Join(".", "log")
  214. }
  215. return "/var/log/x-ui"
  216. }
  217. func copyFile(src, dst string) error {
  218. in, err := os.Open(src)
  219. if err != nil {
  220. return err
  221. }
  222. defer in.Close()
  223. out, err := os.Create(dst)
  224. if err != nil {
  225. return err
  226. }
  227. defer out.Close()
  228. _, err = io.Copy(out, in)
  229. if err != nil {
  230. return err
  231. }
  232. return out.Sync()
  233. }
  234. func init() {
  235. if runtime.GOOS != "windows" {
  236. return
  237. }
  238. if os.Getenv("XUI_DB_FOLDER") != "" {
  239. return
  240. }
  241. oldDBFolder := "/etc/x-ui"
  242. oldDBPath := fmt.Sprintf("%s/%s.db", oldDBFolder, GetName())
  243. newDBFolder := GetDBFolderPath()
  244. newDBPath := fmt.Sprintf("%s/%s.db", newDBFolder, GetName())
  245. _, err := os.Stat(newDBPath)
  246. if err == nil {
  247. return // new exists
  248. }
  249. _, err = os.Stat(oldDBPath)
  250. if os.IsNotExist(err) {
  251. return // old does not exist
  252. }
  253. _ = copyFile(oldDBPath, newDBPath) // ignore error
  254. }