db.go 12 KB

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