1
0

db.go 34 KB

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