db.go 43 KB

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