db.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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. "math"
  11. "os"
  12. "path"
  13. "slices"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/mhsanaei/3x-ui/v3/config"
  18. "github.com/mhsanaei/3x-ui/v3/database/model"
  19. "github.com/mhsanaei/3x-ui/v3/util/crypto"
  20. "github.com/mhsanaei/3x-ui/v3/xray"
  21. "gorm.io/driver/postgres"
  22. "gorm.io/driver/sqlite"
  23. "gorm.io/gorm"
  24. "gorm.io/gorm/logger"
  25. )
  26. var db *gorm.DB
  27. const (
  28. DialectSQLite = "sqlite"
  29. DialectPostgres = "postgres"
  30. )
  31. // IsPostgres reports whether the active connection is a PostgreSQL backend.
  32. func IsPostgres() bool {
  33. if db == nil {
  34. return config.GetDBKind() == "postgres"
  35. }
  36. return db.Dialector.Name() == "postgres"
  37. }
  38. // Dialect returns the active GORM dialect name, or "" if the DB is not open.
  39. func Dialect() string {
  40. if db == nil {
  41. return ""
  42. }
  43. return db.Dialector.Name()
  44. }
  45. const (
  46. defaultUsername = "admin"
  47. defaultPassword = "admin"
  48. )
  49. func initModels() error {
  50. models := []any{
  51. &model.User{},
  52. &model.Inbound{},
  53. &model.OutboundTraffics{},
  54. &model.Setting{},
  55. &model.InboundClientIps{},
  56. &xray.ClientTraffic{},
  57. &model.HistoryOfSeeders{},
  58. &model.CustomGeoResource{},
  59. &model.Node{},
  60. &model.ApiToken{},
  61. &model.ClientRecord{},
  62. &model.ClientInbound{},
  63. &model.ClientGroup{},
  64. &model.InboundFallback{},
  65. }
  66. for _, mdl := range models {
  67. if err := db.AutoMigrate(mdl); err != nil {
  68. if isIgnorableDuplicateColumnErr(err, mdl) {
  69. log.Printf("Ignoring duplicate column during auto migration for %T: %v", mdl, err)
  70. continue
  71. }
  72. log.Printf("Error auto migrating model: %v", err)
  73. return err
  74. }
  75. }
  76. return nil
  77. }
  78. func isIgnorableDuplicateColumnErr(err error, mdl any) bool {
  79. if err == nil {
  80. return false
  81. }
  82. errMsg := strings.ToLower(err.Error())
  83. // SQLite: "duplicate column name: foo"
  84. // Postgres: `pq: column "foo" of relation "bar" already exists` / `sqlstate 42701`
  85. const sqlitePrefix = "duplicate column name:"
  86. if _, after, ok := strings.Cut(errMsg, sqlitePrefix); ok {
  87. col := strings.TrimSpace(after)
  88. col = strings.Trim(col, "`\"[]")
  89. return col != "" && db != nil && db.Migrator().HasColumn(mdl, col)
  90. }
  91. if strings.Contains(errMsg, "already exists") && strings.Contains(errMsg, "column ") {
  92. // Best effort: extract the column name between the first pair of double quotes.
  93. if _, after, ok := strings.Cut(errMsg, "column \""); ok {
  94. rest := after
  95. if e := strings.Index(rest, "\""); e > 0 {
  96. col := rest[:e]
  97. return col != "" && db != nil && db.Migrator().HasColumn(mdl, col)
  98. }
  99. }
  100. }
  101. return false
  102. }
  103. // initUser creates a default admin user if the users table is empty.
  104. func initUser() error {
  105. empty, err := isTableEmpty("users")
  106. if err != nil {
  107. log.Printf("Error checking if users table is empty: %v", err)
  108. return err
  109. }
  110. if empty {
  111. hashedPassword, err := crypto.HashPasswordAsBcrypt(defaultPassword)
  112. if err != nil {
  113. log.Printf("Error hashing default password: %v", err)
  114. return err
  115. }
  116. user := &model.User{
  117. Username: defaultUsername,
  118. Password: hashedPassword,
  119. }
  120. return db.Create(user).Error
  121. }
  122. return nil
  123. }
  124. // runSeeders migrates user passwords to bcrypt and records seeder execution to prevent re-running.
  125. func runSeeders(isUsersEmpty bool) error {
  126. empty, err := isTableEmpty("history_of_seeders")
  127. if err != nil {
  128. log.Printf("Error checking if users table is empty: %v", err)
  129. return err
  130. }
  131. if empty && isUsersEmpty {
  132. seeders := []string{"UserPasswordHash", "ClientsTable", "InboundClientsArrayFix", "InboundClientTgIdFix"}
  133. for _, name := range seeders {
  134. if err := db.Create(&model.HistoryOfSeeders{SeederName: name}).Error; err != nil {
  135. return err
  136. }
  137. }
  138. return seedApiTokens()
  139. }
  140. var seedersHistory []string
  141. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &seedersHistory).Error; err != nil {
  142. log.Printf("Error fetching seeder history: %v", err)
  143. return err
  144. }
  145. if !slices.Contains(seedersHistory, "UserPasswordHash") && !isUsersEmpty {
  146. var users []model.User
  147. if err := db.Find(&users).Error; err != nil {
  148. log.Printf("Error fetching users for password migration: %v", err)
  149. return err
  150. }
  151. for _, user := range users {
  152. hashedPassword, err := crypto.HashPasswordAsBcrypt(user.Password)
  153. if err != nil {
  154. log.Printf("Error hashing password for user '%s': %v", user.Username, err)
  155. return err
  156. }
  157. if err := db.Model(&user).Update("password", hashedPassword).Error; err != nil {
  158. log.Printf("Error updating password for user '%s': %v", user.Username, err)
  159. return err
  160. }
  161. }
  162. hashSeeder := &model.HistoryOfSeeders{
  163. SeederName: "UserPasswordHash",
  164. }
  165. if err := db.Create(hashSeeder).Error; err != nil {
  166. return err
  167. }
  168. }
  169. if !slices.Contains(seedersHistory, "ApiTokensTable") {
  170. if err := seedApiTokens(); err != nil {
  171. return err
  172. }
  173. }
  174. if !slices.Contains(seedersHistory, "ClientsTable") {
  175. if err := seedClientsFromInboundJSON(); err != nil {
  176. return err
  177. }
  178. }
  179. if !slices.Contains(seedersHistory, "InboundClientsArrayFix") {
  180. if err := normalizeInboundClientsArray(); err != nil {
  181. return err
  182. }
  183. }
  184. if !slices.Contains(seedersHistory, "InboundClientTgIdFix") {
  185. if err := normalizeInboundClientTgId(); err != nil {
  186. return err
  187. }
  188. }
  189. return nil
  190. }
  191. func normalizeInboundClientTgId() error {
  192. var inbounds []model.Inbound
  193. if err := db.Find(&inbounds).Error; err != nil {
  194. return err
  195. }
  196. return db.Transaction(func(tx *gorm.DB) error {
  197. for _, inbound := range inbounds {
  198. if strings.TrimSpace(inbound.Settings) == "" {
  199. continue
  200. }
  201. var settings map[string]any
  202. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  203. log.Printf("InboundClientTgIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  204. continue
  205. }
  206. clients, ok := settings["clients"].([]any)
  207. if !ok {
  208. continue
  209. }
  210. mutated := false
  211. for i, raw := range clients {
  212. obj, ok := raw.(map[string]any)
  213. if !ok {
  214. continue
  215. }
  216. tgRaw, present := obj["tgId"]
  217. if !present {
  218. continue
  219. }
  220. v, isFloat := tgRaw.(float64)
  221. if isFloat && !math.IsNaN(v) && !math.IsInf(v, 0) && v == math.Trunc(v) {
  222. continue
  223. }
  224. obj["tgId"] = int64(0)
  225. clients[i] = obj
  226. mutated = true
  227. }
  228. if !mutated {
  229. continue
  230. }
  231. settings["clients"] = clients
  232. newSettings, err := json.MarshalIndent(settings, "", " ")
  233. if err != nil {
  234. log.Printf("InboundClientTgIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  235. continue
  236. }
  237. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  238. Update("settings", string(newSettings)).Error; err != nil {
  239. return err
  240. }
  241. }
  242. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientTgIdFix"}).Error
  243. })
  244. }
  245. func normalizeInboundClientsArray() error {
  246. var inbounds []model.Inbound
  247. if err := db.Find(&inbounds).Error; err != nil {
  248. return err
  249. }
  250. return db.Transaction(func(tx *gorm.DB) error {
  251. for _, inbound := range inbounds {
  252. if strings.TrimSpace(inbound.Settings) == "" {
  253. continue
  254. }
  255. var settings map[string]any
  256. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  257. log.Printf("InboundClientsArrayFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  258. continue
  259. }
  260. raw, exists := settings["clients"]
  261. if !exists || raw != nil {
  262. continue
  263. }
  264. settings["clients"] = []any{}
  265. newSettings, err := json.MarshalIndent(settings, "", " ")
  266. if err != nil {
  267. log.Printf("InboundClientsArrayFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  268. continue
  269. }
  270. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  271. Update("settings", string(newSettings)).Error; err != nil {
  272. return err
  273. }
  274. }
  275. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientsArrayFix"}).Error
  276. })
  277. }
  278. // normalizeClientJSONFields coerces loosely-typed numeric fields in a raw
  279. // settings.clients entry so json.Unmarshal into model.Client doesn't fail
  280. // when older rows wrote tgId/limitIp/totalGB/etc. as strings. Empty strings
  281. // drop the key so the field falls back to its zero value.
  282. func normalizeClientJSONFields(obj map[string]any) {
  283. normalizeInt := func(key string) {
  284. raw, exists := obj[key]
  285. if !exists {
  286. return
  287. }
  288. s, ok := raw.(string)
  289. if !ok {
  290. return
  291. }
  292. trimmed := strings.ReplaceAll(strings.TrimSpace(s), " ", "")
  293. if trimmed == "" {
  294. delete(obj, key)
  295. return
  296. }
  297. if n, err := strconv.ParseInt(trimmed, 10, 64); err == nil {
  298. obj[key] = n
  299. } else {
  300. delete(obj, key)
  301. }
  302. }
  303. for _, k := range []string{"tgId", "limitIp", "totalGB", "expiryTime", "reset", "created_at", "updated_at"} {
  304. normalizeInt(k)
  305. }
  306. }
  307. func seedClientsFromInboundJSON() error {
  308. var inbounds []model.Inbound
  309. if err := db.Find(&inbounds).Error; err != nil {
  310. return err
  311. }
  312. return db.Transaction(func(tx *gorm.DB) error {
  313. byEmail := map[string]*model.ClientRecord{}
  314. var existing []model.ClientRecord
  315. if err := tx.Find(&existing).Error; err != nil {
  316. return err
  317. }
  318. for i := range existing {
  319. byEmail[existing[i].Email] = &existing[i]
  320. }
  321. for _, inbound := range inbounds {
  322. if strings.TrimSpace(inbound.Settings) == "" {
  323. continue
  324. }
  325. var settings map[string]any
  326. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  327. log.Printf("ClientsTable seed: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  328. continue
  329. }
  330. rawList, ok := settings["clients"].([]any)
  331. if !ok {
  332. continue
  333. }
  334. for _, raw := range rawList {
  335. obj, ok := raw.(map[string]any)
  336. if !ok {
  337. continue
  338. }
  339. normalizeClientJSONFields(obj)
  340. blob, err := json.Marshal(obj)
  341. if err != nil {
  342. continue
  343. }
  344. var c model.Client
  345. if err := json.Unmarshal(blob, &c); err != nil {
  346. log.Printf("ClientsTable seed: skip client in inbound %d (unmarshal failed): %v; payload=%s",
  347. inbound.Id, err, string(blob))
  348. continue
  349. }
  350. email := strings.TrimSpace(c.Email)
  351. if email == "" {
  352. continue
  353. }
  354. incoming := c.ToRecord()
  355. row, dup := byEmail[email]
  356. if !dup {
  357. if err := tx.Create(incoming).Error; err != nil {
  358. return err
  359. }
  360. byEmail[email] = incoming
  361. row = incoming
  362. } else {
  363. conflicts := model.MergeClientRecord(row, incoming)
  364. for _, x := range conflicts {
  365. log.Printf("client merge: email=%s conflict on %s old=%v new=%v kept=%v",
  366. email, x.Field, x.Old, x.New, x.Kept)
  367. }
  368. if err := tx.Save(row).Error; err != nil {
  369. return err
  370. }
  371. }
  372. link := model.ClientInbound{
  373. ClientId: row.Id,
  374. InboundId: inbound.Id,
  375. FlowOverride: c.Flow,
  376. }
  377. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  378. FirstOrCreate(&link).Error; err != nil {
  379. return err
  380. }
  381. }
  382. }
  383. return tx.Create(&model.HistoryOfSeeders{SeederName: "ClientsTable"}).Error
  384. })
  385. }
  386. // seedApiTokens copies the legacy `apiToken` setting into the new
  387. // api_tokens table as a row named "default" so existing central panels
  388. // keep working after the upgrade. Idempotent — records itself in
  389. // history_of_seeders and only runs when api_tokens is empty.
  390. func seedApiTokens() error {
  391. empty, err := isTableEmpty("api_tokens")
  392. if err != nil {
  393. return err
  394. }
  395. if empty {
  396. var legacy model.Setting
  397. err := db.Model(model.Setting{}).Where("key = ?", "apiToken").First(&legacy).Error
  398. if err == nil && legacy.Value != "" {
  399. row := &model.ApiToken{
  400. Name: "default",
  401. Token: legacy.Value,
  402. Enabled: true,
  403. }
  404. if err := db.Create(row).Error; err != nil {
  405. log.Printf("Error migrating legacy apiToken: %v", err)
  406. return err
  407. }
  408. }
  409. }
  410. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensTable"}).Error
  411. }
  412. // isTableEmpty returns true if the named table contains zero rows.
  413. func isTableEmpty(tableName string) (bool, error) {
  414. var count int64
  415. err := db.Table(tableName).Count(&count).Error
  416. return count == 0, err
  417. }
  418. // InitDB sets up the database connection, migrates models, and runs seeders.
  419. // When XUI_DB_TYPE=postgres, dbPath is ignored and XUI_DB_DSN is used instead.
  420. func InitDB(dbPath string) error {
  421. var gormLogger logger.Interface
  422. if config.IsDebug() {
  423. gormLogger = logger.New(
  424. log.New(os.Stdout, "\r\n", log.LstdFlags),
  425. logger.Config{
  426. SlowThreshold: time.Second,
  427. LogLevel: logger.Info,
  428. IgnoreRecordNotFoundError: true,
  429. Colorful: true,
  430. },
  431. )
  432. } else {
  433. gormLogger = logger.Discard
  434. }
  435. c := &gorm.Config{Logger: gormLogger}
  436. var err error
  437. switch config.GetDBKind() {
  438. case "postgres":
  439. dsn := config.GetDBDSN()
  440. if dsn == "" {
  441. return errors.New("XUI_DB_TYPE=postgres but XUI_DB_DSN is empty")
  442. }
  443. db, err = gorm.Open(postgres.Open(dsn), c)
  444. if err != nil {
  445. return err
  446. }
  447. default:
  448. dir := path.Dir(dbPath)
  449. if err = os.MkdirAll(dir, 0755); err != nil {
  450. return err
  451. }
  452. dsn := dbPath + "?_journal_mode=WAL&_busy_timeout=10000&_synchronous=NORMAL&_txlock=immediate"
  453. db, err = gorm.Open(sqlite.Open(dsn), c)
  454. if err != nil {
  455. return err
  456. }
  457. sqlDB, err := db.DB()
  458. if err != nil {
  459. return err
  460. }
  461. if _, err := sqlDB.Exec("PRAGMA journal_mode=WAL"); err != nil {
  462. return err
  463. }
  464. if _, err := sqlDB.Exec("PRAGMA busy_timeout=10000"); err != nil {
  465. return err
  466. }
  467. if _, err := sqlDB.Exec("PRAGMA synchronous=NORMAL"); err != nil {
  468. return err
  469. }
  470. }
  471. sqlDB, err := db.DB()
  472. if err != nil {
  473. return err
  474. }
  475. var maxOpen, maxIdle int
  476. switch config.GetDBKind() {
  477. case "postgres":
  478. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 25)
  479. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 25)
  480. default:
  481. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 8)
  482. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 4)
  483. }
  484. sqlDB.SetMaxOpenConns(maxOpen)
  485. sqlDB.SetMaxIdleConns(maxIdle)
  486. sqlDB.SetConnMaxLifetime(time.Hour)
  487. sqlDB.SetConnMaxIdleTime(30 * time.Minute)
  488. if err := initModels(); err != nil {
  489. return err
  490. }
  491. isUsersEmpty, err := isTableEmpty("users")
  492. if err != nil {
  493. return err
  494. }
  495. if err := initUser(); err != nil {
  496. return err
  497. }
  498. return runSeeders(isUsersEmpty)
  499. }
  500. func envInt(key string, def int) int {
  501. v := strings.TrimSpace(os.Getenv(key))
  502. if v == "" {
  503. return def
  504. }
  505. n, err := strconv.Atoi(v)
  506. if err != nil || n <= 0 {
  507. return def
  508. }
  509. return n
  510. }
  511. // CloseDB closes the database connection if it exists.
  512. func CloseDB() error {
  513. if db != nil {
  514. sqlDB, err := db.DB()
  515. if err != nil {
  516. return err
  517. }
  518. return sqlDB.Close()
  519. }
  520. return nil
  521. }
  522. // GetDB returns the global GORM database instance.
  523. func GetDB() *gorm.DB {
  524. return db
  525. }
  526. func IsNotFound(err error) bool {
  527. return errors.Is(err, gorm.ErrRecordNotFound)
  528. }
  529. // IsSQLiteDB checks if the given file is a valid SQLite database by reading its signature.
  530. func IsSQLiteDB(file io.ReaderAt) (bool, error) {
  531. signature := []byte("SQLite format 3\x00")
  532. buf := make([]byte, len(signature))
  533. _, err := file.ReadAt(buf, 0)
  534. if err != nil {
  535. return false, err
  536. }
  537. return bytes.Equal(buf, signature), nil
  538. }
  539. // Checkpoint performs a WAL checkpoint on the SQLite database to ensure data consistency.
  540. // No-op on PostgreSQL (WAL there is managed by the server).
  541. func Checkpoint() error {
  542. if IsPostgres() {
  543. return nil
  544. }
  545. return db.Exec("PRAGMA wal_checkpoint;").Error
  546. }
  547. // ValidateSQLiteDB opens the provided sqlite DB path with a throw-away connection
  548. // and runs a PRAGMA integrity_check to ensure the file is structurally sound.
  549. // It does not mutate global state or run migrations.
  550. func ValidateSQLiteDB(dbPath string) error {
  551. if _, err := os.Stat(dbPath); err != nil { // file must exist
  552. return err
  553. }
  554. gdb, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{Logger: logger.Discard})
  555. if err != nil {
  556. return err
  557. }
  558. sqlDB, err := gdb.DB()
  559. if err != nil {
  560. return err
  561. }
  562. defer sqlDB.Close()
  563. var res string
  564. if err := gdb.Raw("PRAGMA integrity_check;").Scan(&res).Error; err != nil {
  565. return err
  566. }
  567. if res != "ok" {
  568. return errors.New("sqlite integrity check failed: " + res)
  569. }
  570. return nil
  571. }