db.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. // Package database provides database initialization, migration, and management utilities
  2. // for the 3x-ui panel using GORM with SQLite or PostgreSQL.
  3. package database
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "errors"
  8. "io"
  9. "log"
  10. "os"
  11. "path"
  12. "slices"
  13. "strings"
  14. "time"
  15. "github.com/mhsanaei/3x-ui/v3/config"
  16. "github.com/mhsanaei/3x-ui/v3/database/model"
  17. "github.com/mhsanaei/3x-ui/v3/util/crypto"
  18. "github.com/mhsanaei/3x-ui/v3/xray"
  19. "gorm.io/driver/postgres"
  20. "gorm.io/driver/sqlite"
  21. "gorm.io/gorm"
  22. "gorm.io/gorm/logger"
  23. )
  24. var db *gorm.DB
  25. const (
  26. DialectSQLite = "sqlite"
  27. DialectPostgres = "postgres"
  28. )
  29. // IsPostgres reports whether the active connection is a PostgreSQL backend.
  30. func IsPostgres() bool {
  31. if db == nil {
  32. return config.GetDBKind() == "postgres"
  33. }
  34. return db.Dialector.Name() == "postgres"
  35. }
  36. // Dialect returns the active GORM dialect name, or "" if the DB is not open.
  37. func Dialect() string {
  38. if db == nil {
  39. return ""
  40. }
  41. return db.Dialector.Name()
  42. }
  43. const (
  44. defaultUsername = "admin"
  45. defaultPassword = "admin"
  46. )
  47. func initModels() error {
  48. models := []any{
  49. &model.User{},
  50. &model.Inbound{},
  51. &model.OutboundTraffics{},
  52. &model.Setting{},
  53. &model.InboundClientIps{},
  54. &xray.ClientTraffic{},
  55. &model.HistoryOfSeeders{},
  56. &model.CustomGeoResource{},
  57. &model.Node{},
  58. &model.ApiToken{},
  59. &model.ClientRecord{},
  60. &model.ClientInbound{},
  61. &model.InboundFallback{},
  62. }
  63. for _, mdl := range models {
  64. if err := db.AutoMigrate(mdl); err != nil {
  65. if isIgnorableDuplicateColumnErr(err, mdl) {
  66. log.Printf("Ignoring duplicate column during auto migration for %T: %v", mdl, err)
  67. continue
  68. }
  69. log.Printf("Error auto migrating model: %v", err)
  70. return err
  71. }
  72. }
  73. return nil
  74. }
  75. func isIgnorableDuplicateColumnErr(err error, mdl any) bool {
  76. if err == nil {
  77. return false
  78. }
  79. errMsg := strings.ToLower(err.Error())
  80. // SQLite: "duplicate column name: foo"
  81. // Postgres: `pq: column "foo" of relation "bar" already exists` / `sqlstate 42701`
  82. const sqlitePrefix = "duplicate column name:"
  83. if _, after, ok := strings.Cut(errMsg, sqlitePrefix); ok {
  84. col := strings.TrimSpace(after)
  85. col = strings.Trim(col, "`\"[]")
  86. return col != "" && db != nil && db.Migrator().HasColumn(mdl, col)
  87. }
  88. if strings.Contains(errMsg, "already exists") && strings.Contains(errMsg, "column ") {
  89. // Best effort: extract the column name between the first pair of double quotes.
  90. if _, after, ok := strings.Cut(errMsg, "column \""); ok {
  91. rest := after
  92. if e := strings.Index(rest, "\""); e > 0 {
  93. col := rest[:e]
  94. return col != "" && db != nil && db.Migrator().HasColumn(mdl, col)
  95. }
  96. }
  97. }
  98. return false
  99. }
  100. // initUser creates a default admin user if the users table is empty.
  101. func initUser() error {
  102. empty, err := isTableEmpty("users")
  103. if err != nil {
  104. log.Printf("Error checking if users table is empty: %v", err)
  105. return err
  106. }
  107. if empty {
  108. hashedPassword, err := crypto.HashPasswordAsBcrypt(defaultPassword)
  109. if err != nil {
  110. log.Printf("Error hashing default password: %v", err)
  111. return err
  112. }
  113. user := &model.User{
  114. Username: defaultUsername,
  115. Password: hashedPassword,
  116. }
  117. return db.Create(user).Error
  118. }
  119. return nil
  120. }
  121. // runSeeders migrates user passwords to bcrypt and records seeder execution to prevent re-running.
  122. func runSeeders(isUsersEmpty bool) error {
  123. empty, err := isTableEmpty("history_of_seeders")
  124. if err != nil {
  125. log.Printf("Error checking if users table is empty: %v", err)
  126. return err
  127. }
  128. if empty && isUsersEmpty {
  129. hashSeeder := &model.HistoryOfSeeders{
  130. SeederName: "UserPasswordHash",
  131. }
  132. if err := db.Create(hashSeeder).Error; err != nil {
  133. return err
  134. }
  135. return seedApiTokens()
  136. }
  137. var seedersHistory []string
  138. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &seedersHistory).Error; err != nil {
  139. log.Printf("Error fetching seeder history: %v", err)
  140. return err
  141. }
  142. if !slices.Contains(seedersHistory, "UserPasswordHash") && !isUsersEmpty {
  143. var users []model.User
  144. if err := db.Find(&users).Error; err != nil {
  145. log.Printf("Error fetching users for password migration: %v", err)
  146. return err
  147. }
  148. for _, user := range users {
  149. hashedPassword, err := crypto.HashPasswordAsBcrypt(user.Password)
  150. if err != nil {
  151. log.Printf("Error hashing password for user '%s': %v", user.Username, err)
  152. return err
  153. }
  154. if err := db.Model(&user).Update("password", hashedPassword).Error; err != nil {
  155. log.Printf("Error updating password for user '%s': %v", user.Username, err)
  156. return err
  157. }
  158. }
  159. hashSeeder := &model.HistoryOfSeeders{
  160. SeederName: "UserPasswordHash",
  161. }
  162. if err := db.Create(hashSeeder).Error; err != nil {
  163. return err
  164. }
  165. }
  166. if !slices.Contains(seedersHistory, "ApiTokensTable") {
  167. if err := seedApiTokens(); err != nil {
  168. return err
  169. }
  170. }
  171. if !slices.Contains(seedersHistory, "ClientsTable") {
  172. if err := seedClientsFromInboundJSON(); err != nil {
  173. return err
  174. }
  175. }
  176. return nil
  177. }
  178. func seedClientsFromInboundJSON() error {
  179. var inbounds []model.Inbound
  180. if err := db.Find(&inbounds).Error; err != nil {
  181. return err
  182. }
  183. return db.Transaction(func(tx *gorm.DB) error {
  184. byEmail := map[string]*model.ClientRecord{}
  185. for _, inbound := range inbounds {
  186. if strings.TrimSpace(inbound.Settings) == "" {
  187. continue
  188. }
  189. var settings map[string]any
  190. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  191. log.Printf("ClientsTable seed: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  192. continue
  193. }
  194. rawList, ok := settings["clients"].([]any)
  195. if !ok {
  196. continue
  197. }
  198. for _, raw := range rawList {
  199. obj, ok := raw.(map[string]any)
  200. if !ok {
  201. continue
  202. }
  203. blob, err := json.Marshal(obj)
  204. if err != nil {
  205. continue
  206. }
  207. var c model.Client
  208. if err := json.Unmarshal(blob, &c); err != nil {
  209. continue
  210. }
  211. email := strings.TrimSpace(c.Email)
  212. if email == "" {
  213. continue
  214. }
  215. incoming := c.ToRecord()
  216. row, dup := byEmail[email]
  217. if !dup {
  218. if err := tx.Create(incoming).Error; err != nil {
  219. return err
  220. }
  221. byEmail[email] = incoming
  222. row = incoming
  223. } else {
  224. conflicts := model.MergeClientRecord(row, incoming)
  225. for _, x := range conflicts {
  226. log.Printf("client merge: email=%s conflict on %s old=%v new=%v kept=%v",
  227. email, x.Field, x.Old, x.New, x.Kept)
  228. }
  229. if err := tx.Save(row).Error; err != nil {
  230. return err
  231. }
  232. }
  233. link := model.ClientInbound{
  234. ClientId: row.Id,
  235. InboundId: inbound.Id,
  236. FlowOverride: c.Flow,
  237. }
  238. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  239. FirstOrCreate(&link).Error; err != nil {
  240. return err
  241. }
  242. }
  243. }
  244. return tx.Create(&model.HistoryOfSeeders{SeederName: "ClientsTable"}).Error
  245. })
  246. }
  247. // seedApiTokens copies the legacy `apiToken` setting into the new
  248. // api_tokens table as a row named "default" so existing central panels
  249. // keep working after the upgrade. Idempotent — records itself in
  250. // history_of_seeders and only runs when api_tokens is empty.
  251. func seedApiTokens() error {
  252. empty, err := isTableEmpty("api_tokens")
  253. if err != nil {
  254. return err
  255. }
  256. if empty {
  257. var legacy model.Setting
  258. err := db.Model(model.Setting{}).Where("key = ?", "apiToken").First(&legacy).Error
  259. if err == nil && legacy.Value != "" {
  260. row := &model.ApiToken{
  261. Name: "default",
  262. Token: legacy.Value,
  263. Enabled: true,
  264. }
  265. if err := db.Create(row).Error; err != nil {
  266. log.Printf("Error migrating legacy apiToken: %v", err)
  267. return err
  268. }
  269. }
  270. }
  271. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensTable"}).Error
  272. }
  273. // isTableEmpty returns true if the named table contains zero rows.
  274. func isTableEmpty(tableName string) (bool, error) {
  275. var count int64
  276. err := db.Table(tableName).Count(&count).Error
  277. return count == 0, err
  278. }
  279. // InitDB sets up the database connection, migrates models, and runs seeders.
  280. // When XUI_DB_TYPE=postgres, dbPath is ignored and XUI_DB_DSN is used instead.
  281. func InitDB(dbPath string) error {
  282. var gormLogger logger.Interface
  283. if config.IsDebug() {
  284. gormLogger = logger.Default
  285. } else {
  286. gormLogger = logger.Discard
  287. }
  288. c := &gorm.Config{Logger: gormLogger}
  289. var err error
  290. switch config.GetDBKind() {
  291. case "postgres":
  292. dsn := config.GetDBDSN()
  293. if dsn == "" {
  294. return errors.New("XUI_DB_TYPE=postgres but XUI_DB_DSN is empty")
  295. }
  296. db, err = gorm.Open(postgres.Open(dsn), c)
  297. if err != nil {
  298. return err
  299. }
  300. default:
  301. dir := path.Dir(dbPath)
  302. if err = os.MkdirAll(dir, 0755); err != nil {
  303. return err
  304. }
  305. dsn := dbPath + "?_journal_mode=WAL&_busy_timeout=10000&_synchronous=NORMAL&_txlock=immediate"
  306. db, err = gorm.Open(sqlite.Open(dsn), c)
  307. if err != nil {
  308. return err
  309. }
  310. sqlDB, err := db.DB()
  311. if err != nil {
  312. return err
  313. }
  314. if _, err := sqlDB.Exec("PRAGMA journal_mode=WAL"); err != nil {
  315. return err
  316. }
  317. if _, err := sqlDB.Exec("PRAGMA busy_timeout=10000"); err != nil {
  318. return err
  319. }
  320. if _, err := sqlDB.Exec("PRAGMA synchronous=NORMAL"); err != nil {
  321. return err
  322. }
  323. }
  324. sqlDB, err := db.DB()
  325. if err != nil {
  326. return err
  327. }
  328. sqlDB.SetMaxOpenConns(8)
  329. sqlDB.SetMaxIdleConns(4)
  330. sqlDB.SetConnMaxLifetime(time.Hour)
  331. if err := initModels(); err != nil {
  332. return err
  333. }
  334. isUsersEmpty, err := isTableEmpty("users")
  335. if err != nil {
  336. return err
  337. }
  338. if err := initUser(); err != nil {
  339. return err
  340. }
  341. return runSeeders(isUsersEmpty)
  342. }
  343. // CloseDB closes the database connection if it exists.
  344. func CloseDB() error {
  345. if db != nil {
  346. sqlDB, err := db.DB()
  347. if err != nil {
  348. return err
  349. }
  350. return sqlDB.Close()
  351. }
  352. return nil
  353. }
  354. // GetDB returns the global GORM database instance.
  355. func GetDB() *gorm.DB {
  356. return db
  357. }
  358. func IsNotFound(err error) bool {
  359. return errors.Is(err, gorm.ErrRecordNotFound)
  360. }
  361. // IsSQLiteDB checks if the given file is a valid SQLite database by reading its signature.
  362. func IsSQLiteDB(file io.ReaderAt) (bool, error) {
  363. signature := []byte("SQLite format 3\x00")
  364. buf := make([]byte, len(signature))
  365. _, err := file.ReadAt(buf, 0)
  366. if err != nil {
  367. return false, err
  368. }
  369. return bytes.Equal(buf, signature), nil
  370. }
  371. // Checkpoint performs a WAL checkpoint on the SQLite database to ensure data consistency.
  372. // No-op on PostgreSQL (WAL there is managed by the server).
  373. func Checkpoint() error {
  374. if IsPostgres() {
  375. return nil
  376. }
  377. return db.Exec("PRAGMA wal_checkpoint;").Error
  378. }
  379. // ValidateSQLiteDB opens the provided sqlite DB path with a throw-away connection
  380. // and runs a PRAGMA integrity_check to ensure the file is structurally sound.
  381. // It does not mutate global state or run migrations.
  382. func ValidateSQLiteDB(dbPath string) error {
  383. if _, err := os.Stat(dbPath); err != nil { // file must exist
  384. return err
  385. }
  386. gdb, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{Logger: logger.Discard})
  387. if err != nil {
  388. return err
  389. }
  390. sqlDB, err := gdb.DB()
  391. if err != nil {
  392. return err
  393. }
  394. defer sqlDB.Close()
  395. var res string
  396. if err := gdb.Raw("PRAGMA integrity_check;").Scan(&res).Error; err != nil {
  397. return err
  398. }
  399. if res != "ok" {
  400. return errors.New("sqlite integrity check failed: " + res)
  401. }
  402. return nil
  403. }