db.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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. return nil
  615. }
  616. // resetIpLimitsWithoutFail2ban zeroes every client's IP limit on hosts where
  617. // fail2ban can't enforce it (not installed, or the integration disabled). The
  618. // limit silently does nothing there yet kept logging a repeated warning, so a
  619. // stale value is just misleading — the panel also disables the field on these
  620. // hosts. One-time, self-gated on the seeder row.
  621. func resetIpLimitsWithoutFail2ban() error {
  622. var history []string
  623. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  624. return err
  625. }
  626. if slices.Contains(history, "ResetIpLimitNoFail2ban") {
  627. return nil
  628. }
  629. if fail2banCanEnforce() {
  630. return db.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
  631. }
  632. var inbounds []model.Inbound
  633. if err := db.Find(&inbounds).Error; err != nil {
  634. return err
  635. }
  636. return db.Transaction(func(tx *gorm.DB) error {
  637. for _, inbound := range inbounds {
  638. if strings.TrimSpace(inbound.Settings) == "" {
  639. continue
  640. }
  641. var settings map[string]any
  642. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  643. log.Printf("ResetIpLimitNoFail2ban: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  644. continue
  645. }
  646. clients, ok := settings["clients"].([]any)
  647. if !ok {
  648. continue
  649. }
  650. mutated := false
  651. for i, raw := range clients {
  652. obj, ok := raw.(map[string]any)
  653. if !ok {
  654. continue
  655. }
  656. v, present := obj["limitIp"]
  657. if !present {
  658. continue
  659. }
  660. if n, isNum := v.(float64); isNum && n == 0 {
  661. continue
  662. }
  663. obj["limitIp"] = 0
  664. clients[i] = obj
  665. mutated = true
  666. }
  667. if !mutated {
  668. continue
  669. }
  670. settings["clients"] = clients
  671. newSettings, err := json.MarshalIndent(settings, "", " ")
  672. if err != nil {
  673. log.Printf("ResetIpLimitNoFail2ban: skip inbound %d (marshal failed): %v", inbound.Id, err)
  674. continue
  675. }
  676. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  677. Update("settings", string(newSettings)).Error; err != nil {
  678. return err
  679. }
  680. }
  681. if err := tx.Model(&model.ClientRecord{}).Where("limit_ip <> ?", 0).
  682. Update("limit_ip", 0).Error; err != nil {
  683. return err
  684. }
  685. return tx.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
  686. })
  687. }
  688. // fail2banCanEnforce reports whether per-client IP limits can actually be
  689. // enforced on this host: the integration must be enabled (XUI_ENABLE_FAIL2BAN)
  690. // and fail2ban-client must be present. Mirrors the service-layer check, kept
  691. // local to avoid an import cycle.
  692. func fail2banCanEnforce() bool {
  693. if v, ok := os.LookupEnv("XUI_ENABLE_FAIL2BAN"); ok && v != "true" {
  694. return false
  695. }
  696. if runtime.GOOS == "windows" {
  697. return false
  698. }
  699. return exec.CommandContext(context.Background(), "fail2ban-client", "-h").Run() == nil
  700. }
  701. // clearLegacyProxySettings drops the deprecated panelProxy/tgBotProxy rows so a
  702. // stale tgBotProxy no longer masks the panelOutbound egress fallback.
  703. func clearLegacyProxySettings() error {
  704. return db.Transaction(func(tx *gorm.DB) error {
  705. if err := tx.Where("key IN ?", []string{"panelProxy", "tgBotProxy"}).
  706. Delete(&model.Setting{}).Error; err != nil {
  707. return err
  708. }
  709. return tx.Create(&model.HistoryOfSeeders{SeederName: "LegacyProxySettingsCleanup"}).Error
  710. })
  711. }
  712. func normalizeInboundClientTgId() error {
  713. var inbounds []model.Inbound
  714. if err := db.Find(&inbounds).Error; err != nil {
  715. return err
  716. }
  717. return db.Transaction(func(tx *gorm.DB) error {
  718. for _, inbound := range inbounds {
  719. if strings.TrimSpace(inbound.Settings) == "" {
  720. continue
  721. }
  722. var settings map[string]any
  723. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  724. log.Printf("InboundClientTgIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  725. continue
  726. }
  727. clients, ok := settings["clients"].([]any)
  728. if !ok {
  729. continue
  730. }
  731. mutated := false
  732. for i, raw := range clients {
  733. obj, ok := raw.(map[string]any)
  734. if !ok {
  735. continue
  736. }
  737. tgRaw, present := obj["tgId"]
  738. if !present {
  739. continue
  740. }
  741. v, isFloat := tgRaw.(float64)
  742. if isFloat && !math.IsNaN(v) && !math.IsInf(v, 0) && v == math.Trunc(v) {
  743. continue
  744. }
  745. obj["tgId"] = int64(0)
  746. clients[i] = obj
  747. mutated = true
  748. }
  749. if !mutated {
  750. continue
  751. }
  752. settings["clients"] = clients
  753. newSettings, err := json.MarshalIndent(settings, "", " ")
  754. if err != nil {
  755. log.Printf("InboundClientTgIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  756. continue
  757. }
  758. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  759. Update("settings", string(newSettings)).Error; err != nil {
  760. return err
  761. }
  762. }
  763. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientTgIdFix"}).Error
  764. })
  765. }
  766. func normalizeInboundClientSubId() error {
  767. var inbounds []model.Inbound
  768. if err := db.Find(&inbounds).Error; err != nil {
  769. return err
  770. }
  771. return db.Transaction(func(tx *gorm.DB) error {
  772. for _, inbound := range inbounds {
  773. if strings.TrimSpace(inbound.Settings) == "" {
  774. continue
  775. }
  776. var settings map[string]any
  777. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  778. log.Printf("InboundClientSubIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  779. continue
  780. }
  781. clients, ok := settings["clients"].([]any)
  782. if !ok {
  783. continue
  784. }
  785. mutated := false
  786. for i, raw := range clients {
  787. obj, ok := raw.(map[string]any)
  788. if !ok {
  789. continue
  790. }
  791. existing, _ := obj["subId"].(string)
  792. if strings.TrimSpace(existing) != "" {
  793. continue
  794. }
  795. obj["subId"] = random.NumLower(16)
  796. clients[i] = obj
  797. mutated = true
  798. }
  799. if !mutated {
  800. continue
  801. }
  802. settings["clients"] = clients
  803. newSettings, err := json.MarshalIndent(settings, "", " ")
  804. if err != nil {
  805. log.Printf("InboundClientSubIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  806. continue
  807. }
  808. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  809. Update("settings", string(newSettings)).Error; err != nil {
  810. return err
  811. }
  812. }
  813. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientSubIdFix"}).Error
  814. })
  815. }
  816. func normalizeInboundClientsArray() error {
  817. var inbounds []model.Inbound
  818. if err := db.Find(&inbounds).Error; err != nil {
  819. return err
  820. }
  821. return db.Transaction(func(tx *gorm.DB) error {
  822. for _, inbound := range inbounds {
  823. if strings.TrimSpace(inbound.Settings) == "" {
  824. continue
  825. }
  826. var settings map[string]any
  827. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  828. log.Printf("InboundClientsArrayFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  829. continue
  830. }
  831. raw, exists := settings["clients"]
  832. if !exists || raw != nil {
  833. continue
  834. }
  835. settings["clients"] = []any{}
  836. newSettings, err := json.MarshalIndent(settings, "", " ")
  837. if err != nil {
  838. log.Printf("InboundClientsArrayFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  839. continue
  840. }
  841. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  842. Update("settings", string(newSettings)).Error; err != nil {
  843. return err
  844. }
  845. }
  846. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientsArrayFix"}).Error
  847. })
  848. }
  849. func normalizeFreedomFinalRules() error {
  850. var setting model.Setting
  851. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  852. if errors.Is(err, gorm.ErrRecordNotFound) {
  853. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  854. }
  855. if err != nil {
  856. return err
  857. }
  858. updated, changed, rErr := rewriteFreedomFinalRules(setting.Value)
  859. if rErr != nil {
  860. log.Printf("FreedomFinalRulesReverseFix: skip (invalid xrayTemplateConfig json): %v", rErr)
  861. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  862. }
  863. return db.Transaction(func(tx *gorm.DB) error {
  864. if changed {
  865. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  866. Update("value", updated).Error; err != nil {
  867. return err
  868. }
  869. }
  870. return tx.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  871. })
  872. }
  873. func rewriteFreedomFinalRules(raw string) (string, bool, error) {
  874. if strings.TrimSpace(raw) == "" {
  875. return raw, false, nil
  876. }
  877. var cfg map[string]any
  878. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  879. return raw, false, err
  880. }
  881. outbounds, ok := cfg["outbounds"].([]any)
  882. if !ok {
  883. return raw, false, nil
  884. }
  885. changed := false
  886. for _, ob := range outbounds {
  887. obj, ok := ob.(map[string]any)
  888. if !ok {
  889. continue
  890. }
  891. if proto, _ := obj["protocol"].(string); proto != "freedom" {
  892. continue
  893. }
  894. settings, ok := obj["settings"].(map[string]any)
  895. if !ok {
  896. continue
  897. }
  898. if !isLegacyPrivateOnlyFinalRules(settings["finalRules"]) {
  899. continue
  900. }
  901. settings["finalRules"] = []any{map[string]any{"action": "allow"}}
  902. changed = true
  903. }
  904. if !changed {
  905. return raw, false, nil
  906. }
  907. out, err := json.MarshalIndent(cfg, "", " ")
  908. if err != nil {
  909. return raw, false, err
  910. }
  911. return string(out), true, nil
  912. }
  913. func isLegacyPrivateOnlyFinalRules(v any) bool {
  914. rules, ok := v.([]any)
  915. if !ok || len(rules) != 1 {
  916. return false
  917. }
  918. rule, ok := rules[0].(map[string]any)
  919. if !ok {
  920. return false
  921. }
  922. if action, _ := rule["action"].(string); action != "allow" {
  923. return false
  924. }
  925. ips, ok := rule["ip"].([]any)
  926. if !ok || len(ips) != 1 {
  927. return false
  928. }
  929. if s, _ := ips[0].(string); s != "geoip:private" {
  930. return false
  931. }
  932. for k := range rule {
  933. if k != "action" && k != "ip" {
  934. return false
  935. }
  936. }
  937. return true
  938. }
  939. // normalizeClientJSONFields coerces loosely-typed numeric fields in a raw
  940. // settings.clients entry so json.Unmarshal into model.Client doesn't fail
  941. // when older rows wrote tgId/limitIp/totalGB/etc. as strings. Empty strings
  942. // drop the key so the field falls back to its zero value.
  943. func normalizeClientJSONFields(obj map[string]any) {
  944. normalizeInt := func(key string) {
  945. raw, exists := obj[key]
  946. if !exists {
  947. return
  948. }
  949. s, ok := raw.(string)
  950. if !ok {
  951. return
  952. }
  953. trimmed := strings.ReplaceAll(strings.TrimSpace(s), " ", "")
  954. if trimmed == "" {
  955. delete(obj, key)
  956. return
  957. }
  958. if n, err := strconv.ParseInt(trimmed, 10, 64); err == nil {
  959. obj[key] = n
  960. } else {
  961. delete(obj, key)
  962. }
  963. }
  964. for _, k := range []string{"tgId", "limitIp", "totalGB", "expiryTime", "reset", "created_at", "updated_at"} {
  965. normalizeInt(k)
  966. }
  967. }
  968. func seedClientsFromInboundJSON() error {
  969. var inbounds []model.Inbound
  970. if err := db.Find(&inbounds).Error; err != nil {
  971. return err
  972. }
  973. return db.Transaction(func(tx *gorm.DB) error {
  974. byEmail := map[string]*model.ClientRecord{}
  975. var existing []model.ClientRecord
  976. if err := tx.Find(&existing).Error; err != nil {
  977. return err
  978. }
  979. for i := range existing {
  980. byEmail[existing[i].Email] = &existing[i]
  981. }
  982. for _, inbound := range inbounds {
  983. if strings.TrimSpace(inbound.Settings) == "" {
  984. continue
  985. }
  986. var settings map[string]any
  987. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  988. log.Printf("ClientsTable seed: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  989. continue
  990. }
  991. rawList, ok := settings["clients"].([]any)
  992. if !ok {
  993. continue
  994. }
  995. for _, raw := range rawList {
  996. obj, ok := raw.(map[string]any)
  997. if !ok {
  998. continue
  999. }
  1000. normalizeClientJSONFields(obj)
  1001. blob, err := json.Marshal(obj)
  1002. if err != nil {
  1003. continue
  1004. }
  1005. var c model.Client
  1006. if err := json.Unmarshal(blob, &c); err != nil {
  1007. log.Printf("ClientsTable seed: skip client in inbound %d (unmarshal failed): %v; payload=%s",
  1008. inbound.Id, err, string(blob))
  1009. continue
  1010. }
  1011. email := strings.TrimSpace(c.Email)
  1012. if email == "" {
  1013. continue
  1014. }
  1015. incoming := c.ToRecord()
  1016. row, dup := byEmail[email]
  1017. if !dup {
  1018. if err := tx.Create(incoming).Error; err != nil {
  1019. return err
  1020. }
  1021. byEmail[email] = incoming
  1022. row = incoming
  1023. } else {
  1024. conflicts := model.MergeClientRecord(row, incoming)
  1025. for _, x := range conflicts {
  1026. log.Printf("client merge: email=%s conflict on %s old=%v new=%v kept=%v",
  1027. email, x.Field, x.Old, x.New, x.Kept)
  1028. }
  1029. if err := tx.Save(row).Error; err != nil {
  1030. return err
  1031. }
  1032. }
  1033. link := model.ClientInbound{
  1034. ClientId: row.Id,
  1035. InboundId: inbound.Id,
  1036. FlowOverride: c.Flow,
  1037. }
  1038. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  1039. FirstOrCreate(&link).Error; err != nil {
  1040. return err
  1041. }
  1042. }
  1043. }
  1044. return tx.Create(&model.HistoryOfSeeders{SeederName: "ClientsTable"}).Error
  1045. })
  1046. }
  1047. // seedApiTokens copies the legacy `apiToken` setting into the new
  1048. // api_tokens table as a row named "default" so existing central panels
  1049. // keep working after the upgrade. Idempotent — records itself in
  1050. // history_of_seeders and only runs when api_tokens is empty.
  1051. func seedApiTokens() error {
  1052. empty, err := isTableEmpty("api_tokens")
  1053. if err != nil {
  1054. return err
  1055. }
  1056. if empty {
  1057. var legacy model.Setting
  1058. err := db.Model(model.Setting{}).Where("key = ?", "apiToken").First(&legacy).Error
  1059. if err == nil && legacy.Value != "" {
  1060. row := &model.ApiToken{
  1061. Name: "default",
  1062. Token: legacy.Value,
  1063. Enabled: true,
  1064. }
  1065. if err := db.Create(row).Error; err != nil {
  1066. log.Printf("Error migrating legacy apiToken: %v", err)
  1067. return err
  1068. }
  1069. }
  1070. }
  1071. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensTable"}).Error
  1072. }
  1073. // hashExistingApiTokens replaces any plaintext token stored before tokens were
  1074. // hashed at rest with its SHA-256 digest. Callers keep their plaintext copy
  1075. // (used on remote nodes), so existing tokens keep authenticating; the panel
  1076. // just can no longer reveal them. Idempotent — already-hashed rows are skipped.
  1077. func hashExistingApiTokens() error {
  1078. var rows []*model.ApiToken
  1079. if err := db.Find(&rows).Error; err != nil {
  1080. return err
  1081. }
  1082. for _, r := range rows {
  1083. if crypto.IsSHA256Hex(r.Token) {
  1084. continue
  1085. }
  1086. hashed := crypto.HashTokenSHA256(r.Token)
  1087. if err := db.Model(model.ApiToken{}).Where("id = ?", r.Id).Update("token", hashed).Error; err != nil {
  1088. log.Printf("Error hashing api token %d: %v", r.Id, err)
  1089. return err
  1090. }
  1091. }
  1092. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensHash"}).Error
  1093. }
  1094. // isTableEmpty returns true if the named table contains zero rows.
  1095. func isTableEmpty(tableName string) (bool, error) {
  1096. var count int64
  1097. err := db.Table(tableName).Count(&count).Error
  1098. return count == 0, err
  1099. }
  1100. // InitDB sets up the database connection, migrates models, and runs seeders.
  1101. // When XUI_DB_TYPE=postgres, dbPath is ignored and XUI_DB_DSN is used instead.
  1102. func InitDB(dbPath string) error {
  1103. var gormLogger logger.Interface
  1104. if config.IsDebug() {
  1105. gormLogger = logger.New(
  1106. log.New(os.Stdout, "\r\n", log.LstdFlags),
  1107. logger.Config{
  1108. SlowThreshold: time.Second,
  1109. LogLevel: logger.Info,
  1110. IgnoreRecordNotFoundError: true,
  1111. Colorful: true,
  1112. },
  1113. )
  1114. } else {
  1115. gormLogger = logger.Discard
  1116. }
  1117. c := &gorm.Config{Logger: gormLogger, DisableForeignKeyConstraintWhenMigrating: true}
  1118. var err error
  1119. switch config.GetDBKind() {
  1120. case "postgres":
  1121. dsn := config.GetDBDSN()
  1122. if dsn == "" {
  1123. return errors.New("XUI_DB_TYPE=postgres but XUI_DB_DSN is empty")
  1124. }
  1125. db, err = gorm.Open(postgres.Open(dsn), c)
  1126. if err != nil {
  1127. return err
  1128. }
  1129. default:
  1130. dir := path.Dir(dbPath)
  1131. if err = os.MkdirAll(dir, 0o755); err != nil {
  1132. return err
  1133. }
  1134. // Keep journal_mode=DELETE so the DB stays a single file (no -wal/-shm
  1135. // sidecars). synchronous defaults to FULL for durability but is tunable.
  1136. sync := sqliteSynchronous()
  1137. dsn := dbPath + "?_journal_mode=DELETE&_busy_timeout=10000&_synchronous=" + sync + "&_txlock=immediate"
  1138. db, err = gorm.Open(sqlite.Open(dsn), c)
  1139. if err != nil {
  1140. return err
  1141. }
  1142. sqlDB, err := db.DB()
  1143. if err != nil {
  1144. return err
  1145. }
  1146. // Re-assert the DSN pragmas plus scan-friendly ones for large datasets.
  1147. // cache_size/mmap_size/temp_store create no extra files, so the single-file
  1148. // guarantee holds; they just cut disk I/O on the 50k-row hot paths.
  1149. pragmas := []string{
  1150. "PRAGMA journal_mode=DELETE",
  1151. "PRAGMA busy_timeout=10000",
  1152. "PRAGMA synchronous=" + sync,
  1153. fmt.Sprintf("PRAGMA cache_size=-%d", envInt("XUI_DB_CACHE_MB", 32)*1024),
  1154. fmt.Sprintf("PRAGMA mmap_size=%d", int64(envInt("XUI_DB_MMAP_MB", 256))*1024*1024),
  1155. "PRAGMA temp_store=MEMORY",
  1156. }
  1157. for _, p := range pragmas {
  1158. if _, err := sqlDB.ExecContext(context.Background(), p); err != nil {
  1159. return err
  1160. }
  1161. }
  1162. }
  1163. sqlDB, err := db.DB()
  1164. if err != nil {
  1165. return err
  1166. }
  1167. var maxOpen, maxIdle int
  1168. switch config.GetDBKind() {
  1169. case "postgres":
  1170. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 25)
  1171. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 25)
  1172. default:
  1173. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 8)
  1174. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 4)
  1175. }
  1176. sqlDB.SetMaxOpenConns(maxOpen)
  1177. sqlDB.SetMaxIdleConns(maxIdle)
  1178. sqlDB.SetConnMaxLifetime(time.Hour)
  1179. sqlDB.SetConnMaxIdleTime(30 * time.Minute)
  1180. if err := initModels(); err != nil {
  1181. return err
  1182. }
  1183. isUsersEmpty, err := isTableEmpty("users")
  1184. if err != nil {
  1185. return err
  1186. }
  1187. if err := initUser(); err != nil {
  1188. return err
  1189. }
  1190. return runSeeders(isUsersEmpty)
  1191. }
  1192. // normalizeApiTokenCreatedAtSeconds repairs rows written while ApiToken used
  1193. // autoCreateTime:milli. The threshold separates modern Unix milliseconds from
  1194. // Unix seconds and makes this safe to run on every startup.
  1195. func normalizeApiTokenCreatedAtSeconds() error {
  1196. return db.Model(&model.ApiToken{}).
  1197. Where("created_at >= ?", model.ApiTokenUnixMillisecondsThreshold).
  1198. UpdateColumn("created_at", gorm.Expr("created_at / ?", 1000)).Error
  1199. }
  1200. // sqliteSynchronous returns the SQLite synchronous mode, defaulting to FULL.
  1201. // Whitelisted because the value is interpolated directly into a PRAGMA string.
  1202. func sqliteSynchronous() string {
  1203. switch strings.ToUpper(strings.TrimSpace(os.Getenv("XUI_DB_SYNCHRONOUS"))) {
  1204. case "OFF":
  1205. return "OFF"
  1206. case "NORMAL":
  1207. return "NORMAL"
  1208. case "EXTRA":
  1209. return "EXTRA"
  1210. default:
  1211. return "FULL"
  1212. }
  1213. }
  1214. func envInt(key string, def int) int {
  1215. v := strings.TrimSpace(os.Getenv(key))
  1216. if v == "" {
  1217. return def
  1218. }
  1219. n, err := strconv.Atoi(v)
  1220. if err != nil || n <= 0 {
  1221. return def
  1222. }
  1223. return n
  1224. }
  1225. // CloseDB closes the database connection if it exists.
  1226. func CloseDB() error {
  1227. if db != nil {
  1228. sqlDB, err := db.DB()
  1229. if err != nil {
  1230. return err
  1231. }
  1232. return sqlDB.Close()
  1233. }
  1234. return nil
  1235. }
  1236. // GetDB returns the global GORM database instance.
  1237. func GetDB() *gorm.DB {
  1238. return db
  1239. }
  1240. func IsNotFound(err error) bool {
  1241. return errors.Is(err, gorm.ErrRecordNotFound)
  1242. }
  1243. // IsSQLiteDB checks if the given file is a valid SQLite database by reading its signature.
  1244. func IsSQLiteDB(file io.ReaderAt) (bool, error) {
  1245. signature := []byte("SQLite format 3\x00")
  1246. buf := make([]byte, len(signature))
  1247. _, err := file.ReadAt(buf, 0)
  1248. if err != nil {
  1249. return false, err
  1250. }
  1251. return bytes.Equal(buf, signature), nil
  1252. }
  1253. // Checkpoint performs a WAL checkpoint on the SQLite database to ensure data consistency.
  1254. // No-op on PostgreSQL (WAL there is managed by the server).
  1255. func Checkpoint() error {
  1256. if IsPostgres() {
  1257. return nil
  1258. }
  1259. return db.Exec("PRAGMA wal_checkpoint;").Error
  1260. }
  1261. // ValidateSQLiteDB opens the provided sqlite DB path with a throw-away connection
  1262. // and runs a PRAGMA integrity_check to ensure the file is structurally sound.
  1263. // It does not mutate global state or run migrations.
  1264. func ValidateSQLiteDB(dbPath string) error {
  1265. if _, err := os.Stat(dbPath); err != nil { // file must exist
  1266. return err
  1267. }
  1268. gdb, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{Logger: logger.Discard})
  1269. if err != nil {
  1270. return err
  1271. }
  1272. sqlDB, err := gdb.DB()
  1273. if err != nil {
  1274. return err
  1275. }
  1276. defer sqlDB.Close()
  1277. var res string
  1278. if err := gdb.Raw("PRAGMA integrity_check;").Scan(&res).Error; err != nil {
  1279. return err
  1280. }
  1281. if res != "ok" {
  1282. return errors.New("sqlite integrity check failed: " + res)
  1283. }
  1284. return nil
  1285. }