db.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416
  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. "context"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "log"
  12. "math"
  13. "os"
  14. "os/exec"
  15. "path"
  16. "runtime"
  17. "slices"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "github.com/mhsanaei/3x-ui/v3/internal/config"
  22. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  23. "github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
  24. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  25. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  26. "gorm.io/driver/postgres"
  27. "gorm.io/driver/sqlite"
  28. "gorm.io/gorm"
  29. "gorm.io/gorm/logger"
  30. )
  31. var db *gorm.DB
  32. const (
  33. DialectSQLite = "sqlite"
  34. DialectPostgres = "postgres"
  35. )
  36. // IsPostgres reports whether the active connection is a PostgreSQL backend.
  37. func IsPostgres() bool {
  38. if db == nil {
  39. return config.GetDBKind() == "postgres"
  40. }
  41. return db.Name() == "postgres"
  42. }
  43. // Dialect returns the active GORM dialect name, or "" if the DB is not open.
  44. func Dialect() string {
  45. if db == nil {
  46. return ""
  47. }
  48. return db.Name()
  49. }
  50. const (
  51. defaultUsername = "admin"
  52. defaultPassword = "admin"
  53. )
  54. func initModels() error {
  55. models := []any{
  56. &model.User{},
  57. &model.Inbound{},
  58. &model.OutboundTraffics{},
  59. &model.Setting{},
  60. &model.InboundClientIps{},
  61. &xray.ClientTraffic{},
  62. &model.HistoryOfSeeders{},
  63. &model.Node{},
  64. &model.ApiToken{},
  65. &model.ClientRecord{},
  66. &model.ClientInbound{},
  67. &model.ClientExternalLink{},
  68. &model.ClientGroup{},
  69. &model.InboundFallback{},
  70. &model.Host{},
  71. &model.NodeClientTraffic{},
  72. &model.NodeClientIp{},
  73. &model.ClientGlobalTraffic{},
  74. &model.OutboundSubscription{},
  75. }
  76. for _, mdl := range models {
  77. if IsPostgres() && postgresModelSettled(mdl) {
  78. continue
  79. }
  80. if err := db.AutoMigrate(mdl); err != nil {
  81. if isIgnorableDuplicateColumnErr(err, mdl) {
  82. log.Printf("Ignoring duplicate column during auto migration for %T: %v", mdl, err)
  83. continue
  84. }
  85. log.Printf("Error auto migrating model: %v", err)
  86. return err
  87. }
  88. }
  89. if err := migrateHostVerifyPeerCertByNameColumn(); err != nil {
  90. return err
  91. }
  92. if err := normalizeApiTokenCreatedAtSeconds(); err != nil {
  93. return err
  94. }
  95. if err := dropLegacyForeignKeys(); err != nil {
  96. return err
  97. }
  98. if err := pruneOrphanedClientInbounds(); err != nil {
  99. return err
  100. }
  101. if err := pruneOrphanedHosts(); err != nil {
  102. return err
  103. }
  104. if err := normalizeInboundSubSortIndex(); err != nil {
  105. return err
  106. }
  107. if IsPostgres() {
  108. if err := resyncPostgresSequences(db, models); err != nil {
  109. log.Printf("Error resyncing postgres sequences: %v", err)
  110. return err
  111. }
  112. }
  113. return nil
  114. }
  115. // postgresModelSettled skips AutoMigrate when table, columns, and indexes all exist:
  116. // its catalog-filtered column probe misdetects on some setups and re-ADDs columns forever (#5665).
  117. func postgresModelSettled(mdl any) bool {
  118. migrator := db.Migrator()
  119. if !migrator.HasTable(mdl) {
  120. return false
  121. }
  122. stmt := &gorm.Statement{DB: db}
  123. if err := stmt.Parse(mdl); err != nil || stmt.Schema == nil {
  124. return false
  125. }
  126. for _, dbName := range stmt.Schema.DBNames {
  127. if !migrator.HasColumn(mdl, dbName) {
  128. return false
  129. }
  130. }
  131. for _, idx := range stmt.Schema.ParseIndexes() {
  132. if !migrator.HasIndex(mdl, idx.Name) {
  133. return false
  134. }
  135. }
  136. return true
  137. }
  138. func dropLegacyForeignKeys() error {
  139. if !IsPostgres() {
  140. return nil
  141. }
  142. if err := db.Exec("ALTER TABLE client_traffics DROP CONSTRAINT IF EXISTS fk_inbounds_client_stats").Error; err != nil {
  143. log.Printf("Error dropping legacy foreign key fk_inbounds_client_stats: %v", err)
  144. return err
  145. }
  146. return nil
  147. }
  148. // migrateHostVerifyPeerCertByNameColumn converts hosts.verify_peer_cert_by_name
  149. // from its original boolean shape to the comma-separated string xray-core's
  150. // verifyPeerCertByName (vcn) actually expects. The legacy boolean was dead
  151. // (never emitted into links), so its value carries no meaning and is discarded.
  152. // Idempotent by construction (no HistoryOfSeeders row — writing one here would
  153. // flip the fresh-DB detection in runSeeders). Runs right after AutoMigrate,
  154. // before anything reads or writes Host rows (critical on Postgres, where the
  155. // column stays boolean-typed until the ALTER below).
  156. func migrateHostVerifyPeerCertByNameColumn() error {
  157. if !db.Migrator().HasColumn(&model.Host{}, "verify_peer_cert_by_name") {
  158. return nil
  159. }
  160. if IsPostgres() {
  161. // Only convert a still-boolean column; once it is text this is a no-op,
  162. // so a user-set name is never wiped on a later restart.
  163. var dataType string
  164. if err := db.Raw(
  165. `SELECT data_type FROM information_schema.columns WHERE table_name = 'hosts' AND column_name = 'verify_peer_cert_by_name'`,
  166. ).Scan(&dataType).Error; err != nil {
  167. return err
  168. }
  169. if dataType != "boolean" {
  170. return nil
  171. }
  172. if err := db.Exec(`ALTER TABLE hosts ALTER COLUMN verify_peer_cert_by_name DROP DEFAULT`).Error; err != nil {
  173. return err
  174. }
  175. return db.Exec(`ALTER TABLE hosts ALTER COLUMN verify_peer_cert_by_name TYPE text USING ''`).Error
  176. }
  177. // SQLite keeps the original numeric-affinity column; blank any legacy
  178. // integer/null value so it doesn't read back as "0"/"1". After conversion
  179. // every value is text, so re-running touches nothing.
  180. return db.Exec(`UPDATE hosts SET verify_peer_cert_by_name = '' WHERE verify_peer_cert_by_name IS NULL OR typeof(verify_peer_cert_by_name) <> 'text'`).Error
  181. }
  182. // seedHostsFromExternalProxy is a one-time, self-gated migration that creates a
  183. // Host row for every legacy externalProxy entry on every inbound. Additive: the
  184. // externalProxy arrays are left intact in StreamSettings.
  185. func seedHostsFromExternalProxy() error {
  186. var history []string
  187. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  188. return err
  189. }
  190. if slices.Contains(history, "HostsFromExternalProxy") {
  191. return nil
  192. }
  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. for _, inbound := range inbounds {
  199. if _, err := CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  200. return err
  201. }
  202. }
  203. return tx.Create(&model.HistoryOfSeeders{SeederName: "HostsFromExternalProxy"}).Error
  204. })
  205. }
  206. // seedWireguardPeersToClients is a one-time, self-gated migration that converts
  207. // legacy single-config WireGuard inbounds into the multi-client model: each
  208. // settings.peers[] entry becomes a managed client in the clients table attached
  209. // to the inbound, and the inbound settings are rewritten so peers becomes a
  210. // clients[] array (GetXrayConfig re-projects clients back to peers for xray).
  211. // Idempotent: gated on the history row and skipped per-inbound once it already
  212. // has client links.
  213. func seedWireguardPeersToClients() error {
  214. var history []string
  215. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  216. return err
  217. }
  218. if slices.Contains(history, "WireguardPeersToClients") {
  219. return nil
  220. }
  221. var inbounds []model.Inbound
  222. if err := db.Where("protocol = ?", string(model.WireGuard)).Find(&inbounds).Error; err != nil {
  223. return err
  224. }
  225. return db.Transaction(func(tx *gorm.DB) error {
  226. usedEmails := map[string]struct{}{}
  227. var existingEmails []string
  228. if err := tx.Model(&model.ClientRecord{}).Pluck("email", &existingEmails).Error; err != nil {
  229. return err
  230. }
  231. for _, e := range existingEmails {
  232. usedEmails[e] = struct{}{}
  233. }
  234. for _, inbound := range inbounds {
  235. if strings.TrimSpace(inbound.Settings) == "" {
  236. continue
  237. }
  238. var settings map[string]any
  239. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  240. log.Printf("WireguardPeersToClients: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  241. continue
  242. }
  243. peers, ok := settings["peers"].([]any)
  244. if !ok || len(peers) == 0 {
  245. continue
  246. }
  247. var linkCount int64
  248. if err := tx.Model(&model.ClientInbound{}).Where("inbound_id = ?", inbound.Id).Count(&linkCount).Error; err != nil {
  249. return err
  250. }
  251. if linkCount > 0 {
  252. continue
  253. }
  254. clientObjs := make([]any, 0, len(peers))
  255. for i, raw := range peers {
  256. obj, ok := raw.(map[string]any)
  257. if !ok {
  258. continue
  259. }
  260. email := wireguardPeerEmail(inbound.Remark, obj, i, usedEmails)
  261. usedEmails[email] = struct{}{}
  262. obj["email"] = email
  263. if sub, _ := obj["subId"].(string); strings.TrimSpace(sub) == "" {
  264. obj["subId"] = random.NumLower(16)
  265. }
  266. if _, ok := obj["enable"]; !ok {
  267. obj["enable"] = true
  268. }
  269. blob, err := json.Marshal(obj)
  270. if err != nil {
  271. continue
  272. }
  273. var c model.Client
  274. if err := json.Unmarshal(blob, &c); err != nil {
  275. log.Printf("WireguardPeersToClients: skip peer in inbound %d: %v", inbound.Id, err)
  276. continue
  277. }
  278. c.Email = email
  279. incoming := c.ToRecord()
  280. var row model.ClientRecord
  281. err = tx.Where("email = ?", email).First(&row).Error
  282. if errors.Is(err, gorm.ErrRecordNotFound) {
  283. if err := tx.Create(incoming).Error; err != nil {
  284. return err
  285. }
  286. row = *incoming
  287. } else if err != nil {
  288. return err
  289. } else {
  290. model.MergeClientRecord(&row, incoming)
  291. if err := tx.Save(&row).Error; err != nil {
  292. return err
  293. }
  294. }
  295. link := model.ClientInbound{ClientId: row.Id, InboundId: inbound.Id}
  296. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  297. FirstOrCreate(&link).Error; err != nil {
  298. return err
  299. }
  300. clientObjs = append(clientObjs, obj)
  301. }
  302. delete(settings, "peers")
  303. settings["clients"] = clientObjs
  304. newSettings, err := json.Marshal(settings)
  305. if err != nil {
  306. return err
  307. }
  308. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  309. Update("settings", string(newSettings)).Error; err != nil {
  310. return err
  311. }
  312. }
  313. return tx.Create(&model.HistoryOfSeeders{SeederName: "WireguardPeersToClients"}).Error
  314. })
  315. }
  316. // wireguardPeerEmail derives a stable, unique client email for a migrated peer
  317. // from the inbound remark plus the peer's comment (or its 1-based index).
  318. func wireguardPeerEmail(remark string, peer map[string]any, index int, used map[string]struct{}) string {
  319. base := strings.TrimSpace(remark)
  320. if base == "" {
  321. base = "wg"
  322. }
  323. suffix := strconv.Itoa(index + 1)
  324. if c, ok := peer["comment"].(string); ok && strings.TrimSpace(c) != "" {
  325. suffix = strings.TrimSpace(c)
  326. }
  327. email := strings.ReplaceAll(base+"-"+suffix, " ", "-")
  328. candidate := email
  329. for n := 2; ; n++ {
  330. if _, taken := used[candidate]; !taken {
  331. return candidate
  332. }
  333. candidate = email + "-" + strconv.Itoa(n)
  334. }
  335. }
  336. // CreateHostsFromExternalProxy parses a legacy streamSettings.externalProxy array
  337. // and inserts one Host row per entry on tx, returning the number of rows created.
  338. // It is the shared core of both the one-time seedHostsFromExternalProxy startup
  339. // migration and the inbound-import path: an inbound exported from a build that
  340. // predated the hosts table carries its external proxies inline in
  341. // streamSettings.externalProxy, and the startup migration is gated off after its
  342. // first run, so a freshly imported inbound must be converted here instead. Blank
  343. // or malformed streamSettings, or one without externalProxy entries, is a no-op.
  344. func CreateHostsFromExternalProxy(tx *gorm.DB, inboundId int, streamSettings string) (int, error) {
  345. if strings.TrimSpace(streamSettings) == "" {
  346. return 0, nil
  347. }
  348. var stream map[string]any
  349. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  350. return 0, nil
  351. }
  352. eps, ok := stream["externalProxy"].([]any)
  353. if !ok || len(eps) == 0 {
  354. return 0, nil
  355. }
  356. created := 0
  357. for i, raw := range eps {
  358. ep, ok := raw.(map[string]any)
  359. if !ok {
  360. continue
  361. }
  362. if err := tx.Create(externalProxyEntryToHost(inboundId, i, ep)).Error; err != nil {
  363. return created, err
  364. }
  365. created++
  366. }
  367. return created, nil
  368. }
  369. // externalProxyEntryToHost maps one legacy externalProxy entry onto a Host.
  370. // forceTls (same|tls|none) maps straight to Security; an unknown value falls back
  371. // to "same" (inherit). An empty remark gets a stable generated label so the row
  372. // stays valid/editable, and the remark is capped at the model's 256-char limit.
  373. func externalProxyEntryToHost(inboundId, index int, ep map[string]any) *model.Host {
  374. security, _ := ep["forceTls"].(string)
  375. switch security {
  376. case "same", "tls", "none":
  377. default:
  378. security = "same"
  379. }
  380. dest, _ := ep["dest"].(string)
  381. port := 0
  382. if p, ok := ep["port"].(float64); ok {
  383. port = int(p)
  384. }
  385. remark, _ := ep["remark"].(string)
  386. if strings.TrimSpace(remark) == "" {
  387. remark = "imported " + strconv.Itoa(index+1)
  388. }
  389. if len(remark) > 256 {
  390. remark = remark[:256]
  391. }
  392. sni, _ := ep["sni"].(string)
  393. fingerprint, _ := ep["fingerprint"].(string)
  394. ech, _ := ep["echConfigList"].(string)
  395. return &model.Host{
  396. InboundId: inboundId,
  397. SortOrder: index,
  398. Remark: remark,
  399. Address: dest,
  400. Port: port,
  401. Security: security,
  402. Sni: sni,
  403. Fingerprint: fingerprint,
  404. Alpn: anyToNonEmptyStrings(ep["alpn"]),
  405. PinnedPeerCertSha256: anyToNonEmptyStrings(ep["pinnedPeerCertSha256"]),
  406. EchConfigList: ech,
  407. }
  408. }
  409. func anyToNonEmptyStrings(v any) []string {
  410. switch t := v.(type) {
  411. case []any:
  412. out := make([]string, 0, len(t))
  413. for _, e := range t {
  414. if s, ok := e.(string); ok && s != "" {
  415. out = append(out, s)
  416. }
  417. }
  418. return out
  419. case []string:
  420. out := make([]string, 0, len(t))
  421. for _, s := range t {
  422. if s != "" {
  423. out = append(out, s)
  424. }
  425. }
  426. return out
  427. default:
  428. return nil
  429. }
  430. }
  431. func pruneOrphanedHosts() error {
  432. res := db.Exec("DELETE FROM hosts WHERE inbound_id NOT IN (SELECT id FROM inbounds)")
  433. if res.Error != nil {
  434. log.Printf("Error pruning orphaned hosts rows: %v", res.Error)
  435. return res.Error
  436. }
  437. if res.RowsAffected > 0 {
  438. log.Printf("Pruned %d orphaned hosts row(s)", res.RowsAffected)
  439. }
  440. return nil
  441. }
  442. func pruneOrphanedClientInbounds() error {
  443. res := db.Exec("DELETE FROM client_inbounds WHERE inbound_id NOT IN (SELECT id FROM inbounds)")
  444. if res.Error != nil {
  445. log.Printf("Error pruning orphaned client_inbounds rows: %v", res.Error)
  446. return res.Error
  447. }
  448. if res.RowsAffected > 0 {
  449. log.Printf("Pruned %d orphaned client_inbounds row(s)", res.RowsAffected)
  450. }
  451. return nil
  452. }
  453. // normalizeInboundSubSortIndex lifts sub_sort_index values below the 1-based
  454. // minimum (rows written by builds that defaulted the column to 0, or by nodes
  455. // predating the field) so they cannot sort ahead of explicitly ranked inbounds.
  456. func normalizeInboundSubSortIndex() error {
  457. res := db.Exec("UPDATE inbounds SET sub_sort_index = 1 WHERE sub_sort_index < 1")
  458. if res.Error != nil {
  459. log.Printf("Error normalizing inbound sub_sort_index: %v", res.Error)
  460. return res.Error
  461. }
  462. if res.RowsAffected > 0 {
  463. log.Printf("Normalized sub_sort_index on %d inbound(s)", res.RowsAffected)
  464. }
  465. return nil
  466. }
  467. func isIgnorableDuplicateColumnErr(err error, mdl any) bool {
  468. if err == nil {
  469. return false
  470. }
  471. errMsg := strings.ToLower(err.Error())
  472. // SQLite: "duplicate column name: foo"
  473. // Postgres: `pq: column "foo" of relation "bar" already exists` / `sqlstate 42701`
  474. const sqlitePrefix = "duplicate column name:"
  475. if _, after, ok := strings.Cut(errMsg, sqlitePrefix); ok {
  476. col := strings.TrimSpace(after)
  477. col = strings.Trim(col, "`\"[]")
  478. return col != "" && db != nil && db.Migrator().HasColumn(mdl, col)
  479. }
  480. if strings.Contains(errMsg, "already exists") && strings.Contains(errMsg, "column ") {
  481. // Best effort: extract the column name between the first pair of double quotes.
  482. if _, after, ok := strings.Cut(errMsg, "column \""); ok {
  483. rest := after
  484. if e := strings.Index(rest, "\""); e > 0 {
  485. col := rest[:e]
  486. return col != "" && db != nil && db.Migrator().HasColumn(mdl, col)
  487. }
  488. }
  489. }
  490. return false
  491. }
  492. // initUser creates a default admin user if the users table is empty.
  493. func initUser() error {
  494. empty, err := isTableEmpty("users")
  495. if err != nil {
  496. log.Printf("Error checking if users table is empty: %v", err)
  497. return err
  498. }
  499. if empty {
  500. hashedPassword, err := crypto.HashPasswordAsBcrypt(defaultPassword)
  501. if err != nil {
  502. log.Printf("Error hashing default password: %v", err)
  503. return err
  504. }
  505. user := &model.User{
  506. Username: defaultUsername,
  507. Password: hashedPassword,
  508. }
  509. return db.Create(user).Error
  510. }
  511. return nil
  512. }
  513. // runSeeders migrates user passwords to bcrypt and records seeder execution to prevent re-running.
  514. func runSeeders(isUsersEmpty bool) error {
  515. empty, err := isTableEmpty("history_of_seeders")
  516. if err != nil {
  517. log.Printf("Error checking if users table is empty: %v", err)
  518. return err
  519. }
  520. if empty && isUsersEmpty {
  521. seeders := []string{"UserPasswordHash", "ClientsTable", "InboundClientsArrayFix", "InboundClientTgIdFix", "InboundClientSubIdFix", "FreedomFinalRulesReverseFix", "ApiTokensHash", "LegacyProxySettingsCleanup", "WireguardPeersToClients"}
  522. for _, name := range seeders {
  523. if err := db.Create(&model.HistoryOfSeeders{SeederName: name}).Error; err != nil {
  524. return err
  525. }
  526. }
  527. return seedApiTokens()
  528. }
  529. var seedersHistory []string
  530. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &seedersHistory).Error; err != nil {
  531. log.Printf("Error fetching seeder history: %v", err)
  532. return err
  533. }
  534. if !slices.Contains(seedersHistory, "UserPasswordHash") && !isUsersEmpty {
  535. var users []model.User
  536. if err := db.Find(&users).Error; err != nil {
  537. log.Printf("Error fetching users for password migration: %v", err)
  538. return err
  539. }
  540. for _, user := range users {
  541. if crypto.IsHashed(user.Password) {
  542. continue
  543. }
  544. hashedPassword, err := crypto.HashPasswordAsBcrypt(user.Password)
  545. if err != nil {
  546. log.Printf("Error hashing password for user '%s': %v", user.Username, err)
  547. return err
  548. }
  549. if err := db.Model(&user).Update("password", hashedPassword).Error; err != nil {
  550. log.Printf("Error updating password for user '%s': %v", user.Username, err)
  551. return err
  552. }
  553. }
  554. hashSeeder := &model.HistoryOfSeeders{
  555. SeederName: "UserPasswordHash",
  556. }
  557. if err := db.Create(hashSeeder).Error; err != nil {
  558. return err
  559. }
  560. }
  561. if !slices.Contains(seedersHistory, "ApiTokensTable") {
  562. if err := seedApiTokens(); err != nil {
  563. return err
  564. }
  565. }
  566. if !slices.Contains(seedersHistory, "ApiTokensHash") {
  567. if err := hashExistingApiTokens(); err != nil {
  568. return err
  569. }
  570. }
  571. if !slices.Contains(seedersHistory, "ClientsTable") {
  572. if err := seedClientsFromInboundJSON(); err != nil {
  573. return err
  574. }
  575. }
  576. if !slices.Contains(seedersHistory, "InboundClientsArrayFix") {
  577. if err := normalizeInboundClientsArray(); err != nil {
  578. return err
  579. }
  580. }
  581. if !slices.Contains(seedersHistory, "InboundClientTgIdFix") {
  582. if err := normalizeInboundClientTgId(); err != nil {
  583. return err
  584. }
  585. }
  586. if !slices.Contains(seedersHistory, "InboundClientSubIdFix") {
  587. if err := normalizeInboundClientSubId(); err != nil {
  588. return err
  589. }
  590. }
  591. if !slices.Contains(seedersHistory, "FreedomFinalRulesReverseFix") {
  592. if err := normalizeFreedomFinalRules(); err != nil {
  593. return err
  594. }
  595. }
  596. if !slices.Contains(seedersHistory, "LegacyProxySettingsCleanup") {
  597. if err := clearLegacyProxySettings(); err != nil {
  598. return err
  599. }
  600. }
  601. // Self-gated on the "HostsFromExternalProxy" row, so it is safe to call
  602. // unconditionally here.
  603. if err := seedHostsFromExternalProxy(); err != nil {
  604. return err
  605. }
  606. // Self-gated on the "ResetIpLimitNoFail2ban" row.
  607. if err := resetIpLimitsWithoutFail2ban(); err != nil {
  608. return err
  609. }
  610. // Self-gated on the "WireguardPeersToClients" row.
  611. if err := seedWireguardPeersToClients(); err != nil {
  612. return err
  613. }
  614. // Idempotent, not seeder-gated: bad values can re-enter via a restored
  615. // backup, so re-check on every start.
  616. return normalizeSettingPaths()
  617. }
  618. // resetIpLimitsWithoutFail2ban zeroes every client's IP limit on hosts where
  619. // fail2ban can't enforce it (not installed, or the integration disabled). The
  620. // limit silently does nothing there yet kept logging a repeated warning, so a
  621. // stale value is just misleading — the panel also disables the field on these
  622. // hosts. One-time, self-gated on the seeder row.
  623. func resetIpLimitsWithoutFail2ban() error {
  624. var history []string
  625. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  626. return err
  627. }
  628. if slices.Contains(history, "ResetIpLimitNoFail2ban") {
  629. return nil
  630. }
  631. if fail2banCanEnforce() {
  632. return db.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
  633. }
  634. var inbounds []model.Inbound
  635. if err := db.Find(&inbounds).Error; err != nil {
  636. return err
  637. }
  638. return db.Transaction(func(tx *gorm.DB) error {
  639. for _, inbound := range inbounds {
  640. if strings.TrimSpace(inbound.Settings) == "" {
  641. continue
  642. }
  643. var settings map[string]any
  644. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  645. log.Printf("ResetIpLimitNoFail2ban: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  646. continue
  647. }
  648. clients, ok := settings["clients"].([]any)
  649. if !ok {
  650. continue
  651. }
  652. mutated := false
  653. for i, raw := range clients {
  654. obj, ok := raw.(map[string]any)
  655. if !ok {
  656. continue
  657. }
  658. v, present := obj["limitIp"]
  659. if !present {
  660. continue
  661. }
  662. if n, isNum := v.(float64); isNum && n == 0 {
  663. continue
  664. }
  665. obj["limitIp"] = 0
  666. clients[i] = obj
  667. mutated = true
  668. }
  669. if !mutated {
  670. continue
  671. }
  672. settings["clients"] = clients
  673. newSettings, err := json.MarshalIndent(settings, "", " ")
  674. if err != nil {
  675. log.Printf("ResetIpLimitNoFail2ban: skip inbound %d (marshal failed): %v", inbound.Id, err)
  676. continue
  677. }
  678. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  679. Update("settings", string(newSettings)).Error; err != nil {
  680. return err
  681. }
  682. }
  683. if err := tx.Model(&model.ClientRecord{}).Where("limit_ip <> ?", 0).
  684. Update("limit_ip", 0).Error; err != nil {
  685. return err
  686. }
  687. return tx.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
  688. })
  689. }
  690. // fail2banCanEnforce reports whether per-client IP limits can actually be
  691. // enforced on this host: the integration must be enabled (XUI_ENABLE_FAIL2BAN)
  692. // and fail2ban-client must be present. Mirrors the service-layer check, kept
  693. // local to avoid an import cycle.
  694. func fail2banCanEnforce() bool {
  695. if v, ok := os.LookupEnv("XUI_ENABLE_FAIL2BAN"); ok && v != "true" {
  696. return false
  697. }
  698. if runtime.GOOS == "windows" {
  699. return false
  700. }
  701. return exec.CommandContext(context.Background(), "fail2ban-client", "-h").Run() == nil
  702. }
  703. // clearLegacyProxySettings drops the deprecated panelProxy/tgBotProxy rows so a
  704. // stale tgBotProxy no longer masks the panelOutbound egress fallback.
  705. func clearLegacyProxySettings() error {
  706. return db.Transaction(func(tx *gorm.DB) error {
  707. if err := tx.Where("key IN ?", []string{"panelProxy", "tgBotProxy"}).
  708. Delete(&model.Setting{}).Error; err != nil {
  709. return err
  710. }
  711. return tx.Create(&model.HistoryOfSeeders{SeederName: "LegacyProxySettingsCleanup"}).Error
  712. })
  713. }
  714. // normalizeSettingPaths repairs URI-path settings persisted before the
  715. // leading/trailing-slash rules existed (or restored from an old backup),
  716. // mirroring entity.AllSetting.CheckValid. CheckValid self-heals these on save,
  717. // but the frontend rejects the whole Settings form on the bad stored value
  718. // before a save can ever reach it (#5726), so the stored rows themselves must
  719. // be fixed. Idempotent; runs on every start.
  720. func normalizeSettingPaths() error {
  721. pathKeys := []string{"webBasePath", "subPath", "subJsonPath", "subClashPath"}
  722. var rows []model.Setting
  723. if err := db.Where("key IN ?", pathKeys).Find(&rows).Error; err != nil {
  724. return err
  725. }
  726. for _, row := range rows {
  727. fixed := row.Value
  728. if !strings.HasPrefix(fixed, "/") {
  729. fixed = "/" + fixed
  730. }
  731. if !strings.HasSuffix(fixed, "/") {
  732. fixed += "/"
  733. }
  734. if fixed == row.Value {
  735. continue
  736. }
  737. if err := db.Model(&model.Setting{}).Where("id = ?", row.Id).
  738. Update("value", fixed).Error; err != nil {
  739. return err
  740. }
  741. }
  742. return nil
  743. }
  744. func normalizeInboundClientTgId() error {
  745. var inbounds []model.Inbound
  746. if err := db.Find(&inbounds).Error; err != nil {
  747. return err
  748. }
  749. return db.Transaction(func(tx *gorm.DB) error {
  750. for _, inbound := range inbounds {
  751. if strings.TrimSpace(inbound.Settings) == "" {
  752. continue
  753. }
  754. var settings map[string]any
  755. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  756. log.Printf("InboundClientTgIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  757. continue
  758. }
  759. clients, ok := settings["clients"].([]any)
  760. if !ok {
  761. continue
  762. }
  763. mutated := false
  764. for i, raw := range clients {
  765. obj, ok := raw.(map[string]any)
  766. if !ok {
  767. continue
  768. }
  769. tgRaw, present := obj["tgId"]
  770. if !present {
  771. continue
  772. }
  773. v, isFloat := tgRaw.(float64)
  774. if isFloat && !math.IsNaN(v) && !math.IsInf(v, 0) && v == math.Trunc(v) {
  775. continue
  776. }
  777. obj["tgId"] = int64(0)
  778. clients[i] = obj
  779. mutated = true
  780. }
  781. if !mutated {
  782. continue
  783. }
  784. settings["clients"] = clients
  785. newSettings, err := json.MarshalIndent(settings, "", " ")
  786. if err != nil {
  787. log.Printf("InboundClientTgIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  788. continue
  789. }
  790. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  791. Update("settings", string(newSettings)).Error; err != nil {
  792. return err
  793. }
  794. }
  795. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientTgIdFix"}).Error
  796. })
  797. }
  798. func normalizeInboundClientSubId() error {
  799. var inbounds []model.Inbound
  800. if err := db.Find(&inbounds).Error; err != nil {
  801. return err
  802. }
  803. return db.Transaction(func(tx *gorm.DB) error {
  804. for _, inbound := range inbounds {
  805. if strings.TrimSpace(inbound.Settings) == "" {
  806. continue
  807. }
  808. var settings map[string]any
  809. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  810. log.Printf("InboundClientSubIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  811. continue
  812. }
  813. clients, ok := settings["clients"].([]any)
  814. if !ok {
  815. continue
  816. }
  817. mutated := false
  818. for i, raw := range clients {
  819. obj, ok := raw.(map[string]any)
  820. if !ok {
  821. continue
  822. }
  823. existing, _ := obj["subId"].(string)
  824. if strings.TrimSpace(existing) != "" {
  825. continue
  826. }
  827. obj["subId"] = random.NumLower(16)
  828. clients[i] = obj
  829. mutated = true
  830. }
  831. if !mutated {
  832. continue
  833. }
  834. settings["clients"] = clients
  835. newSettings, err := json.MarshalIndent(settings, "", " ")
  836. if err != nil {
  837. log.Printf("InboundClientSubIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  838. continue
  839. }
  840. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  841. Update("settings", string(newSettings)).Error; err != nil {
  842. return err
  843. }
  844. }
  845. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientSubIdFix"}).Error
  846. })
  847. }
  848. func normalizeInboundClientsArray() error {
  849. var inbounds []model.Inbound
  850. if err := db.Find(&inbounds).Error; err != nil {
  851. return err
  852. }
  853. return db.Transaction(func(tx *gorm.DB) error {
  854. for _, inbound := range inbounds {
  855. if strings.TrimSpace(inbound.Settings) == "" {
  856. continue
  857. }
  858. var settings map[string]any
  859. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  860. log.Printf("InboundClientsArrayFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  861. continue
  862. }
  863. raw, exists := settings["clients"]
  864. if !exists || raw != nil {
  865. continue
  866. }
  867. settings["clients"] = []any{}
  868. newSettings, err := json.MarshalIndent(settings, "", " ")
  869. if err != nil {
  870. log.Printf("InboundClientsArrayFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  871. continue
  872. }
  873. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  874. Update("settings", string(newSettings)).Error; err != nil {
  875. return err
  876. }
  877. }
  878. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientsArrayFix"}).Error
  879. })
  880. }
  881. func normalizeFreedomFinalRules() error {
  882. var setting model.Setting
  883. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  884. if errors.Is(err, gorm.ErrRecordNotFound) {
  885. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  886. }
  887. if err != nil {
  888. return err
  889. }
  890. updated, changed, rErr := rewriteFreedomFinalRules(setting.Value)
  891. if rErr != nil {
  892. log.Printf("FreedomFinalRulesReverseFix: skip (invalid xrayTemplateConfig json): %v", rErr)
  893. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  894. }
  895. return db.Transaction(func(tx *gorm.DB) error {
  896. if changed {
  897. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  898. Update("value", updated).Error; err != nil {
  899. return err
  900. }
  901. }
  902. return tx.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  903. })
  904. }
  905. func rewriteFreedomFinalRules(raw string) (string, bool, error) {
  906. if strings.TrimSpace(raw) == "" {
  907. return raw, false, nil
  908. }
  909. var cfg map[string]any
  910. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  911. return raw, false, err
  912. }
  913. outbounds, ok := cfg["outbounds"].([]any)
  914. if !ok {
  915. return raw, false, nil
  916. }
  917. changed := false
  918. for _, ob := range outbounds {
  919. obj, ok := ob.(map[string]any)
  920. if !ok {
  921. continue
  922. }
  923. if proto, _ := obj["protocol"].(string); proto != "freedom" {
  924. continue
  925. }
  926. settings, ok := obj["settings"].(map[string]any)
  927. if !ok {
  928. continue
  929. }
  930. if !isLegacyPrivateOnlyFinalRules(settings["finalRules"]) {
  931. continue
  932. }
  933. settings["finalRules"] = []any{map[string]any{"action": "allow"}}
  934. changed = true
  935. }
  936. if !changed {
  937. return raw, false, nil
  938. }
  939. out, err := json.MarshalIndent(cfg, "", " ")
  940. if err != nil {
  941. return raw, false, err
  942. }
  943. return string(out), true, nil
  944. }
  945. func isLegacyPrivateOnlyFinalRules(v any) bool {
  946. rules, ok := v.([]any)
  947. if !ok || len(rules) != 1 {
  948. return false
  949. }
  950. rule, ok := rules[0].(map[string]any)
  951. if !ok {
  952. return false
  953. }
  954. if action, _ := rule["action"].(string); action != "allow" {
  955. return false
  956. }
  957. ips, ok := rule["ip"].([]any)
  958. if !ok || len(ips) != 1 {
  959. return false
  960. }
  961. if s, _ := ips[0].(string); s != "geoip:private" {
  962. return false
  963. }
  964. for k := range rule {
  965. if k != "action" && k != "ip" {
  966. return false
  967. }
  968. }
  969. return true
  970. }
  971. // normalizeClientJSONFields coerces loosely-typed numeric fields in a raw
  972. // settings.clients entry so json.Unmarshal into model.Client doesn't fail
  973. // when older rows wrote tgId/limitIp/totalGB/etc. as strings. Empty strings
  974. // drop the key so the field falls back to its zero value.
  975. func normalizeClientJSONFields(obj map[string]any) {
  976. normalizeInt := func(key string) {
  977. raw, exists := obj[key]
  978. if !exists {
  979. return
  980. }
  981. s, ok := raw.(string)
  982. if !ok {
  983. return
  984. }
  985. trimmed := strings.ReplaceAll(strings.TrimSpace(s), " ", "")
  986. if trimmed == "" {
  987. delete(obj, key)
  988. return
  989. }
  990. if n, err := strconv.ParseInt(trimmed, 10, 64); err == nil {
  991. obj[key] = n
  992. } else {
  993. delete(obj, key)
  994. }
  995. }
  996. for _, k := range []string{"tgId", "limitIp", "totalGB", "expiryTime", "reset", "created_at", "updated_at"} {
  997. normalizeInt(k)
  998. }
  999. }
  1000. func seedClientsFromInboundJSON() error {
  1001. var inbounds []model.Inbound
  1002. if err := db.Find(&inbounds).Error; err != nil {
  1003. return err
  1004. }
  1005. return db.Transaction(func(tx *gorm.DB) error {
  1006. byEmail := map[string]*model.ClientRecord{}
  1007. var existing []model.ClientRecord
  1008. if err := tx.Find(&existing).Error; err != nil {
  1009. return err
  1010. }
  1011. for i := range existing {
  1012. byEmail[existing[i].Email] = &existing[i]
  1013. }
  1014. for _, inbound := range inbounds {
  1015. if strings.TrimSpace(inbound.Settings) == "" {
  1016. continue
  1017. }
  1018. var settings map[string]any
  1019. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1020. log.Printf("ClientsTable seed: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1021. continue
  1022. }
  1023. rawList, ok := settings["clients"].([]any)
  1024. if !ok {
  1025. continue
  1026. }
  1027. for _, raw := range rawList {
  1028. obj, ok := raw.(map[string]any)
  1029. if !ok {
  1030. continue
  1031. }
  1032. normalizeClientJSONFields(obj)
  1033. blob, err := json.Marshal(obj)
  1034. if err != nil {
  1035. continue
  1036. }
  1037. var c model.Client
  1038. if err := json.Unmarshal(blob, &c); err != nil {
  1039. log.Printf("ClientsTable seed: skip client in inbound %d (unmarshal failed): %v; payload=%s",
  1040. inbound.Id, err, string(blob))
  1041. continue
  1042. }
  1043. email := strings.TrimSpace(c.Email)
  1044. if email == "" {
  1045. continue
  1046. }
  1047. incoming := c.ToRecord()
  1048. row, dup := byEmail[email]
  1049. if !dup {
  1050. if err := tx.Create(incoming).Error; err != nil {
  1051. return err
  1052. }
  1053. byEmail[email] = incoming
  1054. row = incoming
  1055. } else {
  1056. conflicts := model.MergeClientRecord(row, incoming)
  1057. for _, x := range conflicts {
  1058. log.Printf("client merge: email=%s conflict on %s old=%v new=%v kept=%v",
  1059. email, x.Field, x.Old, x.New, x.Kept)
  1060. }
  1061. if err := tx.Save(row).Error; err != nil {
  1062. return err
  1063. }
  1064. }
  1065. link := model.ClientInbound{
  1066. ClientId: row.Id,
  1067. InboundId: inbound.Id,
  1068. FlowOverride: c.Flow,
  1069. }
  1070. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  1071. FirstOrCreate(&link).Error; err != nil {
  1072. return err
  1073. }
  1074. }
  1075. }
  1076. return tx.Create(&model.HistoryOfSeeders{SeederName: "ClientsTable"}).Error
  1077. })
  1078. }
  1079. // seedApiTokens copies the legacy `apiToken` setting into the new
  1080. // api_tokens table as a row named "default" so existing central panels
  1081. // keep working after the upgrade. Idempotent — records itself in
  1082. // history_of_seeders and only runs when api_tokens is empty.
  1083. func seedApiTokens() error {
  1084. empty, err := isTableEmpty("api_tokens")
  1085. if err != nil {
  1086. return err
  1087. }
  1088. if empty {
  1089. var legacy model.Setting
  1090. err := db.Model(model.Setting{}).Where("key = ?", "apiToken").First(&legacy).Error
  1091. if err == nil && legacy.Value != "" {
  1092. row := &model.ApiToken{
  1093. Name: "default",
  1094. Token: legacy.Value,
  1095. Enabled: true,
  1096. }
  1097. if err := db.Create(row).Error; err != nil {
  1098. log.Printf("Error migrating legacy apiToken: %v", err)
  1099. return err
  1100. }
  1101. }
  1102. }
  1103. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensTable"}).Error
  1104. }
  1105. // hashExistingApiTokens replaces any plaintext token stored before tokens were
  1106. // hashed at rest with its SHA-256 digest. Callers keep their plaintext copy
  1107. // (used on remote nodes), so existing tokens keep authenticating; the panel
  1108. // just can no longer reveal them. Idempotent — already-hashed rows are skipped.
  1109. func hashExistingApiTokens() error {
  1110. var rows []*model.ApiToken
  1111. if err := db.Find(&rows).Error; err != nil {
  1112. return err
  1113. }
  1114. for _, r := range rows {
  1115. if crypto.IsSHA256Hex(r.Token) {
  1116. continue
  1117. }
  1118. hashed := crypto.HashTokenSHA256(r.Token)
  1119. if err := db.Model(model.ApiToken{}).Where("id = ?", r.Id).Update("token", hashed).Error; err != nil {
  1120. log.Printf("Error hashing api token %d: %v", r.Id, err)
  1121. return err
  1122. }
  1123. }
  1124. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensHash"}).Error
  1125. }
  1126. // isTableEmpty returns true if the named table contains zero rows.
  1127. func isTableEmpty(tableName string) (bool, error) {
  1128. var count int64
  1129. err := db.Table(tableName).Count(&count).Error
  1130. return count == 0, err
  1131. }
  1132. // InitDB sets up the database connection, migrates models, and runs seeders.
  1133. // When XUI_DB_TYPE=postgres, dbPath is ignored and XUI_DB_DSN is used instead.
  1134. func InitDB(dbPath string) error {
  1135. var gormLogger logger.Interface
  1136. if config.IsDebug() {
  1137. gormLogger = logger.New(
  1138. log.New(os.Stdout, "\r\n", log.LstdFlags),
  1139. logger.Config{
  1140. SlowThreshold: time.Second,
  1141. LogLevel: logger.Info,
  1142. IgnoreRecordNotFoundError: true,
  1143. Colorful: true,
  1144. },
  1145. )
  1146. } else {
  1147. gormLogger = logger.Discard
  1148. }
  1149. c := &gorm.Config{Logger: gormLogger, DisableForeignKeyConstraintWhenMigrating: true}
  1150. var err error
  1151. switch config.GetDBKind() {
  1152. case "postgres":
  1153. dsn := config.GetDBDSN()
  1154. if dsn == "" {
  1155. return errors.New("XUI_DB_TYPE=postgres but XUI_DB_DSN is empty")
  1156. }
  1157. db, err = gorm.Open(postgres.Open(dsn), c)
  1158. if err != nil {
  1159. return err
  1160. }
  1161. default:
  1162. dir := path.Dir(dbPath)
  1163. if err = os.MkdirAll(dir, 0o755); err != nil {
  1164. return err
  1165. }
  1166. // Keep journal_mode=DELETE so the DB stays a single file (no -wal/-shm
  1167. // sidecars). synchronous defaults to FULL for durability but is tunable.
  1168. sync := sqliteSynchronous()
  1169. dsn := dbPath + "?_journal_mode=DELETE&_busy_timeout=10000&_synchronous=" + sync + "&_txlock=immediate"
  1170. db, err = gorm.Open(sqlite.Open(dsn), c)
  1171. if err != nil {
  1172. return err
  1173. }
  1174. sqlDB, err := db.DB()
  1175. if err != nil {
  1176. return err
  1177. }
  1178. // Re-assert the DSN pragmas plus scan-friendly ones for large datasets.
  1179. // cache_size/mmap_size/temp_store create no extra files, so the single-file
  1180. // guarantee holds; they just cut disk I/O on the 50k-row hot paths.
  1181. pragmas := []string{
  1182. "PRAGMA journal_mode=DELETE",
  1183. "PRAGMA busy_timeout=10000",
  1184. "PRAGMA synchronous=" + sync,
  1185. fmt.Sprintf("PRAGMA cache_size=-%d", envInt("XUI_DB_CACHE_MB", 32)*1024),
  1186. fmt.Sprintf("PRAGMA mmap_size=%d", int64(envInt("XUI_DB_MMAP_MB", 256))*1024*1024),
  1187. "PRAGMA temp_store=MEMORY",
  1188. }
  1189. for _, p := range pragmas {
  1190. if _, err := sqlDB.ExecContext(context.Background(), p); err != nil {
  1191. return err
  1192. }
  1193. }
  1194. }
  1195. sqlDB, err := db.DB()
  1196. if err != nil {
  1197. return err
  1198. }
  1199. var maxOpen, maxIdle int
  1200. switch config.GetDBKind() {
  1201. case "postgres":
  1202. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 25)
  1203. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 25)
  1204. default:
  1205. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 8)
  1206. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 4)
  1207. }
  1208. sqlDB.SetMaxOpenConns(maxOpen)
  1209. sqlDB.SetMaxIdleConns(maxIdle)
  1210. sqlDB.SetConnMaxLifetime(time.Hour)
  1211. sqlDB.SetConnMaxIdleTime(30 * time.Minute)
  1212. if err := initModels(); err != nil {
  1213. return err
  1214. }
  1215. isUsersEmpty, err := isTableEmpty("users")
  1216. if err != nil {
  1217. return err
  1218. }
  1219. if err := initUser(); err != nil {
  1220. return err
  1221. }
  1222. return runSeeders(isUsersEmpty)
  1223. }
  1224. // normalizeApiTokenCreatedAtSeconds repairs rows written while ApiToken used
  1225. // autoCreateTime:milli. The threshold separates modern Unix milliseconds from
  1226. // Unix seconds and makes this safe to run on every startup.
  1227. func normalizeApiTokenCreatedAtSeconds() error {
  1228. return db.Model(&model.ApiToken{}).
  1229. Where("created_at >= ?", model.ApiTokenUnixMillisecondsThreshold).
  1230. UpdateColumn("created_at", gorm.Expr("created_at / ?", 1000)).Error
  1231. }
  1232. // sqliteSynchronous returns the SQLite synchronous mode, defaulting to FULL.
  1233. // Whitelisted because the value is interpolated directly into a PRAGMA string.
  1234. func sqliteSynchronous() string {
  1235. switch strings.ToUpper(strings.TrimSpace(os.Getenv("XUI_DB_SYNCHRONOUS"))) {
  1236. case "OFF":
  1237. return "OFF"
  1238. case "NORMAL":
  1239. return "NORMAL"
  1240. case "EXTRA":
  1241. return "EXTRA"
  1242. default:
  1243. return "FULL"
  1244. }
  1245. }
  1246. func envInt(key string, def int) int {
  1247. v := strings.TrimSpace(os.Getenv(key))
  1248. if v == "" {
  1249. return def
  1250. }
  1251. n, err := strconv.Atoi(v)
  1252. if err != nil || n <= 0 {
  1253. return def
  1254. }
  1255. return n
  1256. }
  1257. // CloseDB closes the database connection if it exists.
  1258. func CloseDB() error {
  1259. if db != nil {
  1260. sqlDB, err := db.DB()
  1261. if err != nil {
  1262. return err
  1263. }
  1264. return sqlDB.Close()
  1265. }
  1266. return nil
  1267. }
  1268. // GetDB returns the global GORM database instance.
  1269. func GetDB() *gorm.DB {
  1270. return db
  1271. }
  1272. func IsNotFound(err error) bool {
  1273. return errors.Is(err, gorm.ErrRecordNotFound)
  1274. }
  1275. // IsSQLiteDB checks if the given file is a valid SQLite database by reading its signature.
  1276. func IsSQLiteDB(file io.ReaderAt) (bool, error) {
  1277. signature := []byte("SQLite format 3\x00")
  1278. buf := make([]byte, len(signature))
  1279. _, err := file.ReadAt(buf, 0)
  1280. if err != nil {
  1281. return false, err
  1282. }
  1283. return bytes.Equal(buf, signature), nil
  1284. }
  1285. // Checkpoint performs a WAL checkpoint on the SQLite database to ensure data consistency.
  1286. // No-op on PostgreSQL (WAL there is managed by the server).
  1287. func Checkpoint() error {
  1288. if IsPostgres() {
  1289. return nil
  1290. }
  1291. return db.Exec("PRAGMA wal_checkpoint;").Error
  1292. }
  1293. // ValidateSQLiteDB opens the provided sqlite DB path with a throw-away connection
  1294. // and runs a PRAGMA integrity_check to ensure the file is structurally sound.
  1295. // It does not mutate global state or run migrations.
  1296. func ValidateSQLiteDB(dbPath string) error {
  1297. if _, err := os.Stat(dbPath); err != nil { // file must exist
  1298. return err
  1299. }
  1300. gdb, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{Logger: logger.Discard})
  1301. if err != nil {
  1302. return err
  1303. }
  1304. sqlDB, err := gdb.DB()
  1305. if err != nil {
  1306. return err
  1307. }
  1308. defer sqlDB.Close()
  1309. var res string
  1310. if err := gdb.Raw("PRAGMA integrity_check;").Scan(&res).Error; err != nil {
  1311. return err
  1312. }
  1313. if res != "ok" {
  1314. return errors.New("sqlite integrity check failed: " + res)
  1315. }
  1316. return nil
  1317. }