config.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. // GetVersion returns the version string of the 3x-ui application.
  38. func GetVersion() string {
  39. return strings.TrimSpace(version)
  40. }
  41. // GetName returns the name of the 3x-ui application.
  42. func GetName() string {
  43. return strings.TrimSpace(name)
  44. }
  45. // GetBuildCommit returns the short git commit this binary was built from, or an
  46. // empty string for a plain/local build or a stable tagged release.
  47. func GetBuildCommit() string {
  48. return strings.TrimSpace(buildCommit)
  49. }
  50. // GetBuildDate returns the UTC build timestamp injected at build time, or empty.
  51. func GetBuildDate() string {
  52. return strings.TrimSpace(buildDate)
  53. }
  54. // IsDevBuild reports whether this binary is a CI per-commit (dev channel) build,
  55. // detected by the injected commit. Stable releases and local builds return false.
  56. func IsDevBuild() bool {
  57. return GetBuildCommit() != ""
  58. }
  59. // GetReportedVersion returns the version a panel advertises to a managing master
  60. // node: the plain version for stable builds, or "dev+<short commit>" for dev
  61. // builds. The dev form mirrors the master's getPanelUpdateInfo latestVersion so
  62. // a node on the current dev commit compares as up to date instead of always
  63. // showing "update available".
  64. func GetReportedVersion() string {
  65. if !IsDevBuild() {
  66. return GetVersion()
  67. }
  68. commit := GetBuildCommit()
  69. if len(commit) > 8 {
  70. commit = commit[:8]
  71. }
  72. return "dev+" + commit
  73. }
  74. // GetLogLevel returns the current logging level based on environment variables or defaults to Info.
  75. func GetLogLevel() LogLevel {
  76. if IsDebug() {
  77. return Debug
  78. }
  79. logLevel := os.Getenv("XUI_LOG_LEVEL")
  80. if logLevel == "" {
  81. return Info
  82. }
  83. return LogLevel(logLevel)
  84. }
  85. // IsDebug returns true if debug mode is enabled via the XUI_DEBUG environment variable.
  86. func IsDebug() bool {
  87. return os.Getenv("XUI_DEBUG") == "true"
  88. }
  89. // IsSkipHSTS returns true if skipping HSTS mode is enabled via the XUI_SKIP_HSTS environment variable.
  90. func IsSkipHSTS() bool {
  91. return os.Getenv("XUI_SKIP_HSTS") == "true"
  92. }
  93. func GetPortOverride() (port int, configured bool, err error) {
  94. value, ok := os.LookupEnv("XUI_PORT")
  95. if !ok || strings.TrimSpace(value) == "" {
  96. return 0, false, nil
  97. }
  98. port, err = strconv.Atoi(strings.TrimSpace(value))
  99. if err != nil {
  100. return 0, true, fmt.Errorf("parse XUI_PORT: %w", err)
  101. }
  102. if port < 1 || port > 65535 {
  103. return 0, true, fmt.Errorf("XUI_PORT must be between 1 and 65535")
  104. }
  105. return port, true, nil
  106. }
  107. // GetBinFolderPath returns the path to the binary folder, defaulting to "bin" if not set via XUI_BIN_FOLDER.
  108. func GetBinFolderPath() string {
  109. binFolderPath := os.Getenv("XUI_BIN_FOLDER")
  110. if binFolderPath == "" {
  111. binFolderPath = "bin"
  112. }
  113. return binFolderPath
  114. }
  115. func getBaseDir() string {
  116. exePath, err := os.Executable()
  117. if err != nil {
  118. return "."
  119. }
  120. exeDir := filepath.Dir(exePath)
  121. exeDirLower := strings.ToLower(filepath.ToSlash(exeDir))
  122. if strings.Contains(exeDirLower, "/appdata/local/temp/") || strings.Contains(exeDirLower, "/go-build") {
  123. wd, err := os.Getwd()
  124. if err != nil {
  125. return "."
  126. }
  127. return wd
  128. }
  129. return exeDir
  130. }
  131. // GetDBFolderPath returns the path to the database folder based on environment variables or platform defaults.
  132. func GetDBFolderPath() string {
  133. dbFolderPath := os.Getenv("XUI_DB_FOLDER")
  134. if dbFolderPath != "" {
  135. return dbFolderPath
  136. }
  137. if runtime.GOOS == "windows" {
  138. return getBaseDir()
  139. }
  140. return "/etc/x-ui"
  141. }
  142. // GetDBPath returns the full path to the database file.
  143. func GetDBPath() string {
  144. return fmt.Sprintf("%s/%s.db", GetDBFolderPath(), GetName())
  145. }
  146. // GetDBKind returns the configured database backend: "sqlite" (default) or "postgres".
  147. func GetDBKind() string {
  148. v := strings.ToLower(strings.TrimSpace(os.Getenv("XUI_DB_TYPE")))
  149. switch v {
  150. case "postgres", "postgresql", "pg":
  151. return "postgres"
  152. default:
  153. return "sqlite"
  154. }
  155. }
  156. // GetDBDSN returns the PostgreSQL DSN from XUI_DB_DSN. Empty for sqlite.
  157. func GetDBDSN() string {
  158. return strings.TrimSpace(os.Getenv("XUI_DB_DSN"))
  159. }
  160. // GetEnvFilePaths returns the candidate service environment file paths (the file
  161. // systemd loads via EnvironmentFile) across the supported distro families.
  162. func GetEnvFilePaths() []string {
  163. if runtime.GOOS == "windows" {
  164. return nil
  165. }
  166. return []string{
  167. "/etc/default/x-ui",
  168. "/etc/conf.d/x-ui",
  169. "/etc/sysconfig/x-ui",
  170. }
  171. }
  172. // GetLogFolder returns the path to the log folder based on environment variables or platform defaults.
  173. func GetLogFolder() string {
  174. logFolderPath := os.Getenv("XUI_LOG_FOLDER")
  175. if logFolderPath != "" {
  176. return logFolderPath
  177. }
  178. // Under `go test` the Windows default below is CWD-relative ("./log"), which
  179. // scatters a log/ directory through the source tree (one per tested package).
  180. // Redirect test runs to a shared temp folder so the source tree stays clean.
  181. if testing.Testing() {
  182. return filepath.Join(os.TempDir(), "3x-ui-test-log")
  183. }
  184. if runtime.GOOS == "windows" {
  185. return filepath.Join(".", "log")
  186. }
  187. return "/var/log/x-ui"
  188. }
  189. func copyFile(src, dst string) error {
  190. in, err := os.Open(src)
  191. if err != nil {
  192. return err
  193. }
  194. defer in.Close()
  195. out, err := os.Create(dst)
  196. if err != nil {
  197. return err
  198. }
  199. defer out.Close()
  200. _, err = io.Copy(out, in)
  201. if err != nil {
  202. return err
  203. }
  204. return out.Sync()
  205. }
  206. func init() {
  207. if runtime.GOOS != "windows" {
  208. return
  209. }
  210. if os.Getenv("XUI_DB_FOLDER") != "" {
  211. return
  212. }
  213. oldDBFolder := "/etc/x-ui"
  214. oldDBPath := fmt.Sprintf("%s/%s.db", oldDBFolder, GetName())
  215. newDBFolder := GetDBFolderPath()
  216. newDBPath := fmt.Sprintf("%s/%s.db", newDBFolder, GetName())
  217. _, err := os.Stat(newDBPath)
  218. if err == nil {
  219. return // new exists
  220. }
  221. _, err = os.Stat(oldDBPath)
  222. if os.IsNotExist(err) {
  223. return // old does not exist
  224. }
  225. _ = copyFile(oldDBPath, newDBPath) // ignore error
  226. }