db.go 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293
  1. package database
  2. import (
  3. "bytes"
  4. "context"
  5. "database/sql"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log"
  11. "math"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  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. "github.com/mattn/go-sqlite3"
  27. "gorm.io/driver/postgres"
  28. "gorm.io/driver/sqlite"
  29. "gorm.io/gorm"
  30. "gorm.io/gorm/logger"
  31. )
  32. var db *gorm.DB
  33. var backupSQLiteTimeout = 2 * time.Minute
  34. const (
  35. DialectSQLite = "sqlite"
  36. DialectPostgres = "postgres"
  37. )
  38. func IsPostgres() bool {
  39. if db == nil {
  40. return config.GetDBKind() == "postgres"
  41. }
  42. return db.Name() == "postgres"
  43. }
  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. sqliteBackupDirPrefix = ".x-ui-backup-"
  54. )
  55. func allModels() []any {
  56. return []any{
  57. &model.User{},
  58. &model.Inbound{},
  59. &model.OutboundTraffics{},
  60. &model.Setting{},
  61. &model.InboundClientIps{},
  62. &xray.ClientTraffic{},
  63. &model.HistoryOfSeeders{},
  64. &model.Node{},
  65. &model.ApiToken{},
  66. &model.ClientRecord{},
  67. &model.ClientInbound{},
  68. &model.ClientExternalLink{},
  69. &model.ClientGroup{},
  70. &model.InboundFallback{},
  71. &model.Host{},
  72. &model.NodeClientTraffic{},
  73. &model.NodeClientIp{},
  74. &model.ClientGlobalTraffic{},
  75. &model.OutboundSubscription{},
  76. }
  77. }
  78. func migrateClientTrafficLastSubFetchColumn() error {
  79. migrator := db.Migrator()
  80. if !migrator.HasTable(&xray.ClientTraffic{}) || migrator.HasColumn(&xray.ClientTraffic{}, "last_sub_fetch") {
  81. return nil
  82. }
  83. return migrator.AddColumn(&xray.ClientTraffic{}, "LastSubFetch")
  84. }
  85. func initModels() error {
  86. if err := migrateClientTrafficLastSubFetchColumn(); err != nil {
  87. return err
  88. }
  89. models := allModels()
  90. for _, mdl := range models {
  91. if IsPostgres() && postgresModelSettled(mdl) {
  92. continue
  93. }
  94. if err := db.AutoMigrate(mdl); err != nil {
  95. if isIgnorableDuplicateColumnErr(db, err, mdl) {
  96. log.Printf("Ignoring duplicate column during auto migration for %T: %v", mdl, err)
  97. continue
  98. }
  99. log.Printf("Error auto migrating model: %v", err)
  100. return err
  101. }
  102. }
  103. if err := dropLegacyInboundPortUnique(); err != nil {
  104. return err
  105. }
  106. if err := migrateHostVerifyPeerCertByNameColumn(); err != nil {
  107. return err
  108. }
  109. if err := normalizeApiTokenCreatedAtSeconds(); err != nil {
  110. return err
  111. }
  112. if err := dropLegacyForeignKeys(); err != nil {
  113. return err
  114. }
  115. if err := pruneOrphanedClientInbounds(); err != nil {
  116. return err
  117. }
  118. if err := pruneOrphanedHosts(); err != nil {
  119. return err
  120. }
  121. if err := normalizeInboundSubSortIndex(); err != nil {
  122. return err
  123. }
  124. if err := repairOverflowedTrafficCounters(); err != nil {
  125. return err
  126. }
  127. if err := dedupeInboundSettingsClients(); err != nil {
  128. return err
  129. }
  130. if err := migrateLegacySocksInboundsToMixed(); err != nil {
  131. return err
  132. }
  133. if err := migrateShadowsocksRemovedCiphers(); err != nil {
  134. return err
  135. }
  136. if err := migrateVmessRemovedSecurities(); err != nil {
  137. return err
  138. }
  139. if err := migrateTgIDIndex(); err != nil {
  140. return err
  141. }
  142. if err := migrateSyncOrphanColumns(); err != nil {
  143. return err
  144. }
  145. if IsPostgres() {
  146. if err := resyncPostgresSequences(db, models); err != nil {
  147. log.Printf("Error resyncing postgres sequences: %v", err)
  148. return err
  149. }
  150. }
  151. return nil
  152. }
  153. func postgresModelSettled(mdl any) bool {
  154. migrator := db.Migrator()
  155. if !migrator.HasTable(mdl) {
  156. return false
  157. }
  158. stmt := &gorm.Statement{DB: db}
  159. if err := stmt.Parse(mdl); err != nil || stmt.Schema == nil {
  160. return false
  161. }
  162. for _, dbName := range stmt.Schema.DBNames {
  163. if !migrator.HasColumn(mdl, dbName) {
  164. return false
  165. }
  166. }
  167. for _, idx := range stmt.Schema.ParseIndexes() {
  168. if !migrator.HasIndex(mdl, idx.Name) {
  169. return false
  170. }
  171. }
  172. return true
  173. }
  174. func dropLegacyForeignKeys() error {
  175. if !IsPostgres() {
  176. return nil
  177. }
  178. if err := db.Exec("ALTER TABLE client_traffics DROP CONSTRAINT IF EXISTS fk_inbounds_client_stats").Error; err != nil {
  179. log.Printf("Error dropping legacy foreign key fk_inbounds_client_stats: %v", err)
  180. return err
  181. }
  182. return nil
  183. }
  184. type sqliteIndexListRow struct {
  185. Name string `gorm:"column:name"`
  186. Unique int `gorm:"column:unique"`
  187. Origin string `gorm:"column:origin"`
  188. }
  189. func sqliteUniquePortIndexes() (autoIndexes, explicitIndexes []string, err error) {
  190. var list []sqliteIndexListRow
  191. if err = db.Raw(`PRAGMA index_list('inbounds')`).Scan(&list).Error; err != nil {
  192. return nil, nil, err
  193. }
  194. for _, idx := range list {
  195. if idx.Unique != 1 {
  196. continue
  197. }
  198. var cols []struct {
  199. Name string `gorm:"column:name"`
  200. }
  201. if err = db.Raw(`PRAGMA index_info("` + idx.Name + `")`).Scan(&cols).Error; err != nil {
  202. return nil, nil, err
  203. }
  204. if len(cols) != 1 || cols[0].Name != "port" {
  205. continue
  206. }
  207. if idx.Origin == "c" {
  208. explicitIndexes = append(explicitIndexes, idx.Name)
  209. } else {
  210. autoIndexes = append(autoIndexes, idx.Name)
  211. }
  212. }
  213. return autoIndexes, explicitIndexes, nil
  214. }
  215. // dropLegacyInboundPortUnique removes the pre-multi-node UNIQUE on inbounds.port,
  216. // which AutoMigrate never drops and which blocks cross-node port reuse on old SQLite DBs.
  217. func dropLegacyInboundPortUnique() error {
  218. if IsPostgres() {
  219. return nil
  220. }
  221. autoIndexes, explicitIndexes, err := sqliteUniquePortIndexes()
  222. if err != nil {
  223. return err
  224. }
  225. for _, name := range explicitIndexes {
  226. if err := db.Exec(`DROP INDEX IF EXISTS "` + name + `"`).Error; err != nil {
  227. return err
  228. }
  229. }
  230. if len(autoIndexes) == 0 {
  231. return nil
  232. }
  233. log.Printf("Rebuilding inbounds table to drop the legacy UNIQUE constraint on port")
  234. return rebuildInboundsWithoutInlineUniquePort()
  235. }
  236. func sqliteTableColumns(tx *gorm.DB, table string) ([]string, error) {
  237. var rows []struct {
  238. Name string `gorm:"column:name"`
  239. }
  240. if err := tx.Raw(`PRAGMA table_info("` + table + `")`).Scan(&rows).Error; err != nil {
  241. return nil, err
  242. }
  243. cols := make([]string, 0, len(rows))
  244. for _, r := range rows {
  245. cols = append(cols, r.Name)
  246. }
  247. return cols, nil
  248. }
  249. func rebuildInboundsWithoutInlineUniquePort() error {
  250. return db.Transaction(func(tx *gorm.DB) error {
  251. var list []sqliteIndexListRow
  252. if err := tx.Raw(`PRAGMA index_list('inbounds')`).Scan(&list).Error; err != nil {
  253. return err
  254. }
  255. for _, idx := range list {
  256. if idx.Origin != "c" {
  257. continue
  258. }
  259. if err := tx.Exec(`DROP INDEX IF EXISTS "` + idx.Name + `"`).Error; err != nil {
  260. return err
  261. }
  262. }
  263. if err := tx.Exec(`ALTER TABLE inbounds RENAME TO inbounds_legacy_rebuild`).Error; err != nil {
  264. return err
  265. }
  266. if err := tx.Migrator().CreateTable(&model.Inbound{}); err != nil {
  267. return err
  268. }
  269. newCols, err := sqliteTableColumns(tx, "inbounds")
  270. if err != nil {
  271. return err
  272. }
  273. oldCols, err := sqliteTableColumns(tx, "inbounds_legacy_rebuild")
  274. if err != nil {
  275. return err
  276. }
  277. oldSet := make(map[string]struct{}, len(oldCols))
  278. for _, c := range oldCols {
  279. oldSet[c] = struct{}{}
  280. }
  281. shared := make([]string, 0, len(newCols))
  282. for _, c := range newCols {
  283. if _, ok := oldSet[c]; ok {
  284. shared = append(shared, `"`+c+`"`)
  285. }
  286. }
  287. colList := strings.Join(shared, ", ")
  288. if err := tx.Exec(`INSERT INTO inbounds (` + colList + `) SELECT ` + colList + ` FROM inbounds_legacy_rebuild`).Error; err != nil {
  289. return err
  290. }
  291. return tx.Exec(`DROP TABLE inbounds_legacy_rebuild`).Error
  292. })
  293. }
  294. // AutoMigrate adds the column; this only backfills the NULLs an older SQLite
  295. // ALTER TABLE leaves behind, so the reaper's predicate never compares to NULL.
  296. func migrateSyncOrphanColumns() error {
  297. if !db.Migrator().HasColumn(&model.ClientRecord{}, "sync_orphaned_at") {
  298. return nil
  299. }
  300. return db.Exec("UPDATE clients SET sync_orphaned_at = 0 WHERE sync_orphaned_at IS NULL").Error
  301. }
  302. func migrateHostVerifyPeerCertByNameColumn() error {
  303. if !db.Migrator().HasColumn(&model.Host{}, "verify_peer_cert_by_name") {
  304. return nil
  305. }
  306. if IsPostgres() {
  307. var dataType string
  308. if err := db.Raw(
  309. `SELECT data_type FROM information_schema.columns WHERE table_name = 'hosts' AND column_name = 'verify_peer_cert_by_name'`,
  310. ).Scan(&dataType).Error; err != nil {
  311. return err
  312. }
  313. if dataType != "boolean" {
  314. return nil
  315. }
  316. if err := db.Exec(`ALTER TABLE hosts ALTER COLUMN verify_peer_cert_by_name DROP DEFAULT`).Error; err != nil {
  317. return err
  318. }
  319. return db.Exec(`ALTER TABLE hosts ALTER COLUMN verify_peer_cert_by_name TYPE text USING ''`).Error
  320. }
  321. 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
  322. }
  323. func seedHostsFromExternalProxy() error {
  324. var history []string
  325. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  326. return err
  327. }
  328. if slices.Contains(history, "HostsFromExternalProxy") {
  329. return nil
  330. }
  331. var inbounds []model.Inbound
  332. if err := db.Find(&inbounds).Error; err != nil {
  333. return err
  334. }
  335. return db.Transaction(func(tx *gorm.DB) error {
  336. for _, inbound := range inbounds {
  337. if _, err := CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  338. return err
  339. }
  340. }
  341. return tx.Create(&model.HistoryOfSeeders{SeederName: "HostsFromExternalProxy"}).Error
  342. })
  343. }
  344. func seedWireguardPeersToClients() error {
  345. var history []string
  346. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  347. return err
  348. }
  349. if slices.Contains(history, "WireguardPeersToClients") {
  350. return nil
  351. }
  352. var inbounds []model.Inbound
  353. if err := db.Where("protocol = ?", string(model.WireGuard)).Find(&inbounds).Error; err != nil {
  354. return err
  355. }
  356. return db.Transaction(func(tx *gorm.DB) error {
  357. usedEmails := map[string]struct{}{}
  358. var existingEmails []string
  359. if err := tx.Model(&model.ClientRecord{}).Pluck("email", &existingEmails).Error; err != nil {
  360. return err
  361. }
  362. for _, e := range existingEmails {
  363. usedEmails[e] = struct{}{}
  364. }
  365. for _, inbound := range inbounds {
  366. if strings.TrimSpace(inbound.Settings) == "" {
  367. continue
  368. }
  369. var settings map[string]any
  370. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  371. log.Printf("WireguardPeersToClients: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  372. continue
  373. }
  374. peers, ok := settings["peers"].([]any)
  375. if !ok || len(peers) == 0 {
  376. continue
  377. }
  378. var linkCount int64
  379. if err := tx.Model(&model.ClientInbound{}).Where("inbound_id = ?", inbound.Id).Count(&linkCount).Error; err != nil {
  380. return err
  381. }
  382. if linkCount > 0 {
  383. continue
  384. }
  385. clientObjs := make([]any, 0, len(peers))
  386. for i, raw := range peers {
  387. obj, ok := raw.(map[string]any)
  388. if !ok {
  389. continue
  390. }
  391. email := wireguardPeerEmail(inbound.Remark, obj, i, usedEmails)
  392. usedEmails[email] = struct{}{}
  393. obj["email"] = email
  394. if sub, _ := obj["subId"].(string); strings.TrimSpace(sub) == "" {
  395. obj["subId"] = random.NumLower(16)
  396. }
  397. if _, ok := obj["enable"]; !ok {
  398. obj["enable"] = true
  399. }
  400. blob, err := json.Marshal(obj)
  401. if err != nil {
  402. continue
  403. }
  404. var c model.Client
  405. if err := json.Unmarshal(blob, &c); err != nil {
  406. log.Printf("WireguardPeersToClients: skip peer in inbound %d: %v", inbound.Id, err)
  407. continue
  408. }
  409. c.Email = email
  410. incoming := c.ToRecord()
  411. var row model.ClientRecord
  412. err = tx.Where("email = ?", email).First(&row).Error
  413. if errors.Is(err, gorm.ErrRecordNotFound) {
  414. if err := tx.Create(incoming).Error; err != nil {
  415. return err
  416. }
  417. row = *incoming
  418. } else if err != nil {
  419. return err
  420. } else {
  421. model.MergeClientRecord(&row, incoming)
  422. if err := tx.Save(&row).Error; err != nil {
  423. return err
  424. }
  425. }
  426. link := model.ClientInbound{ClientId: row.Id, InboundId: inbound.Id}
  427. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  428. FirstOrCreate(&link).Error; err != nil {
  429. return err
  430. }
  431. clientObjs = append(clientObjs, obj)
  432. }
  433. delete(settings, "peers")
  434. settings["clients"] = clientObjs
  435. newSettings, err := json.Marshal(settings)
  436. if err != nil {
  437. return err
  438. }
  439. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  440. Update("settings", string(newSettings)).Error; err != nil {
  441. return err
  442. }
  443. }
  444. return tx.Create(&model.HistoryOfSeeders{SeederName: "WireguardPeersToClients"}).Error
  445. })
  446. }
  447. func wireguardPeerEmail(remark string, peer map[string]any, index int, used map[string]struct{}) string {
  448. base := strings.TrimSpace(remark)
  449. if base == "" {
  450. base = "wg"
  451. }
  452. suffix := strconv.Itoa(index + 1)
  453. if c, ok := peer["comment"].(string); ok && strings.TrimSpace(c) != "" {
  454. suffix = strings.TrimSpace(c)
  455. }
  456. email := strings.ReplaceAll(base+"-"+suffix, " ", "-")
  457. candidate := email
  458. for n := 2; ; n++ {
  459. if _, taken := used[candidate]; !taken {
  460. return candidate
  461. }
  462. candidate = email + "-" + strconv.Itoa(n)
  463. }
  464. }
  465. // seedMtprotoSecretsToClients converts each legacy single-secret mtproto inbound
  466. // into a one-client inbound so MTProto joins the shared multi-client model: the
  467. // inbound-level secret becomes the first client's FakeTLS secret, and a
  468. // ClientRecord + client_inbounds link are created so per-client traffic, limits,
  469. // and share links work exactly like every other protocol. One-time, self-gated
  470. // on the "MtprotoSecretsToClients" seeder row. Mirrors seedWireguardPeersToClients.
  471. func seedMtprotoSecretsToClients() error {
  472. var history []string
  473. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  474. return err
  475. }
  476. if slices.Contains(history, "MtprotoSecretsToClients") {
  477. return nil
  478. }
  479. var inbounds []model.Inbound
  480. if err := db.Where("protocol = ?", string(model.MTProto)).Find(&inbounds).Error; err != nil {
  481. return err
  482. }
  483. return db.Transaction(func(tx *gorm.DB) error {
  484. usedEmails := map[string]struct{}{}
  485. var existingEmails []string
  486. if err := tx.Model(&model.ClientRecord{}).Pluck("email", &existingEmails).Error; err != nil {
  487. return err
  488. }
  489. for _, e := range existingEmails {
  490. usedEmails[e] = struct{}{}
  491. }
  492. for _, inbound := range inbounds {
  493. if strings.TrimSpace(inbound.Settings) == "" {
  494. continue
  495. }
  496. var settings map[string]any
  497. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  498. log.Printf("MtprotoSecretsToClients: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  499. continue
  500. }
  501. if clients, ok := settings["clients"].([]any); ok && len(clients) > 0 {
  502. continue
  503. }
  504. var linkCount int64
  505. if err := tx.Model(&model.ClientInbound{}).Where("inbound_id = ?", inbound.Id).Count(&linkCount).Error; err != nil {
  506. return err
  507. }
  508. if linkCount > 0 {
  509. continue
  510. }
  511. secret, _ := settings["secret"].(string)
  512. secret = strings.TrimSpace(secret)
  513. if secret == "" {
  514. domain, _ := settings["fakeTlsDomain"].(string)
  515. secret = model.GenerateFakeTLSSecret(strings.TrimSpace(domain))
  516. }
  517. email := mtprotoInboundClientEmail(inbound.Remark, usedEmails)
  518. usedEmails[email] = struct{}{}
  519. obj := map[string]any{
  520. "email": email,
  521. "secret": secret,
  522. "enable": true,
  523. "subId": random.NumLower(16),
  524. }
  525. c := model.Client{Email: email, Secret: secret, Enable: true, SubID: obj["subId"].(string)}
  526. incoming := c.ToRecord()
  527. var row model.ClientRecord
  528. err := tx.Where("email = ?", email).First(&row).Error
  529. if errors.Is(err, gorm.ErrRecordNotFound) {
  530. if err := tx.Create(incoming).Error; err != nil {
  531. return err
  532. }
  533. row = *incoming
  534. } else if err != nil {
  535. return err
  536. } else {
  537. model.MergeClientRecord(&row, incoming)
  538. if err := tx.Save(&row).Error; err != nil {
  539. return err
  540. }
  541. }
  542. link := model.ClientInbound{ClientId: row.Id, InboundId: inbound.Id}
  543. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  544. FirstOrCreate(&link).Error; err != nil {
  545. return err
  546. }
  547. delete(settings, "secret")
  548. settings["clients"] = []any{obj}
  549. newSettings, err := json.Marshal(settings)
  550. if err != nil {
  551. return err
  552. }
  553. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  554. Update("settings", string(newSettings)).Error; err != nil {
  555. return err
  556. }
  557. }
  558. return tx.Create(&model.HistoryOfSeeders{SeederName: "MtprotoSecretsToClients"}).Error
  559. })
  560. }
  561. // stripMtprotoInboundSecrets removes the vestigial inbound-level `secret` from
  562. // every mtproto inbound. seedMtprotoSecretsToClients already drops it while
  563. // converting legacy single-secret inbounds, but inbounds that already had clients
  564. // kept the dead field, and the old HealMtprotoSecret regenerated it on every
  565. // save. mtg and every share link read only per-client secrets, so the
  566. // inbound-level value is dead data that once leaked into stale, unusable links.
  567. // One-time, self-gated on the "StripMtprotoInboundSecrets" seeder row.
  568. func stripMtprotoInboundSecrets() error {
  569. var history []string
  570. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  571. return err
  572. }
  573. if slices.Contains(history, "StripMtprotoInboundSecrets") {
  574. return nil
  575. }
  576. var inbounds []model.Inbound
  577. if err := db.Where("protocol = ?", string(model.MTProto)).Find(&inbounds).Error; err != nil {
  578. return err
  579. }
  580. return db.Transaction(func(tx *gorm.DB) error {
  581. for _, inbound := range inbounds {
  582. stripped, ok := model.StripMtprotoInboundSecret(inbound.Settings)
  583. if !ok {
  584. continue
  585. }
  586. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  587. Update("settings", stripped).Error; err != nil {
  588. return err
  589. }
  590. }
  591. return tx.Create(&model.HistoryOfSeeders{SeederName: "StripMtprotoInboundSecrets"}).Error
  592. })
  593. }
  594. // mtprotoInboundClientEmail derives a stable, unique client email for a migrated
  595. // mtproto inbound from its remark.
  596. func mtprotoInboundClientEmail(remark string, used map[string]struct{}) string {
  597. base := strings.TrimSpace(remark)
  598. if base == "" {
  599. base = "mtproto"
  600. }
  601. email := strings.ReplaceAll(base, " ", "-")
  602. candidate := email
  603. for n := 2; ; n++ {
  604. if _, taken := used[candidate]; !taken {
  605. return candidate
  606. }
  607. candidate = email + "-" + strconv.Itoa(n)
  608. }
  609. }
  610. // CreateHostsFromExternalProxy parses a legacy streamSettings.externalProxy array
  611. // and inserts one Host row per entry on tx, returning the number of rows created.
  612. // It is the shared core of both the one-time seedHostsFromExternalProxy startup
  613. // migration and the inbound-import path: an inbound exported from a build that
  614. // predated the hosts table carries its external proxies inline in
  615. // streamSettings.externalProxy, and the startup migration is gated off after its
  616. // first run, so a freshly imported inbound must be converted here instead. Blank
  617. // or malformed streamSettings, or one without externalProxy entries, is a no-op.
  618. func CreateHostsFromExternalProxy(tx *gorm.DB, inboundId int, streamSettings string) (int, error) {
  619. if strings.TrimSpace(streamSettings) == "" {
  620. return 0, nil
  621. }
  622. var stream map[string]any
  623. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  624. return 0, nil
  625. }
  626. eps, ok := stream["externalProxy"].([]any)
  627. if !ok || len(eps) == 0 {
  628. return 0, nil
  629. }
  630. created := 0
  631. for i, raw := range eps {
  632. ep, ok := raw.(map[string]any)
  633. if !ok {
  634. continue
  635. }
  636. if err := tx.Create(externalProxyEntryToHost(inboundId, i, ep)).Error; err != nil {
  637. return created, err
  638. }
  639. created++
  640. }
  641. return created, nil
  642. }
  643. func externalProxyEntryToHost(inboundId, index int, ep map[string]any) *model.Host {
  644. security, _ := ep["forceTls"].(string)
  645. switch security {
  646. case "same", "tls", "none":
  647. default:
  648. security = "same"
  649. }
  650. dest, _ := ep["dest"].(string)
  651. port := 0
  652. if p, ok := ep["port"].(float64); ok {
  653. port = int(p)
  654. }
  655. remark, _ := ep["remark"].(string)
  656. if strings.TrimSpace(remark) == "" {
  657. remark = "imported " + strconv.Itoa(index+1)
  658. }
  659. if len(remark) > 256 {
  660. remark = remark[:256]
  661. }
  662. sni, _ := ep["sni"].(string)
  663. fingerprint, _ := ep["fingerprint"].(string)
  664. ech, _ := ep["echConfigList"].(string)
  665. return &model.Host{
  666. GroupId: random.NumLower(16),
  667. InboundId: inboundId,
  668. SortOrder: index,
  669. Remark: remark,
  670. Address: dest,
  671. Port: port,
  672. Security: security,
  673. Sni: sni,
  674. Fingerprint: fingerprint,
  675. Alpn: anyToNonEmptyStrings(ep["alpn"]),
  676. PinnedPeerCertSha256: anyToNonEmptyStrings(ep["pinnedPeerCertSha256"]),
  677. EchConfigList: ech,
  678. }
  679. }
  680. func anyToNonEmptyStrings(v any) []string {
  681. switch t := v.(type) {
  682. case []any:
  683. out := make([]string, 0, len(t))
  684. for _, e := range t {
  685. if s, ok := e.(string); ok && s != "" {
  686. out = append(out, s)
  687. }
  688. }
  689. return out
  690. case []string:
  691. out := make([]string, 0, len(t))
  692. for _, s := range t {
  693. if s != "" {
  694. out = append(out, s)
  695. }
  696. }
  697. return out
  698. default:
  699. return nil
  700. }
  701. }
  702. func pruneOrphanedHosts() error {
  703. res := db.Exec("DELETE FROM hosts WHERE inbound_id NOT IN (SELECT id FROM inbounds)")
  704. if res.Error != nil {
  705. log.Printf("Error pruning orphaned hosts rows: %v", res.Error)
  706. return res.Error
  707. }
  708. if res.RowsAffected > 0 {
  709. log.Printf("Pruned %d orphaned hosts row(s)", res.RowsAffected)
  710. }
  711. return nil
  712. }
  713. func pruneOrphanedClientInbounds() error {
  714. res := db.Exec("DELETE FROM client_inbounds WHERE inbound_id NOT IN (SELECT id FROM inbounds)")
  715. if res.Error != nil {
  716. log.Printf("Error pruning orphaned client_inbounds rows: %v", res.Error)
  717. return res.Error
  718. }
  719. if res.RowsAffected > 0 {
  720. log.Printf("Pruned %d orphaned client_inbounds row(s)", res.RowsAffected)
  721. }
  722. return nil
  723. }
  724. // migrateLegacySocksInboundsToMixed renames legacy socks inbounds to mixed.
  725. // The protocol enum dropped socks in favor of mixed (identical settings shape,
  726. // same behavior plus HTTP on the shared port), so rows predating the rename
  727. // fail model validation — most visibly when pushed to a node, where one legacy
  728. // inbound stalled the entire node's config and traffic sync (#5685).
  729. func migrateLegacySocksInboundsToMixed() error {
  730. res := db.Exec("UPDATE inbounds SET protocol = 'mixed' WHERE protocol = 'socks'")
  731. if res.Error != nil {
  732. log.Printf("Error migrating legacy socks inbounds to mixed: %v", res.Error)
  733. return res.Error
  734. }
  735. if res.RowsAffected > 0 {
  736. log.Printf("Migrated %d legacy socks inbound(s) to mixed", res.RowsAffected)
  737. }
  738. return nil
  739. }
  740. // migrateShadowsocksRemovedCiphers rewrites shadowsocks inbounds still using
  741. // the "none"/"plain" ciphers that xray-core v26.7.11 removed; one such row
  742. // makes the whole generated config unbuildable and keeps xray from starting.
  743. func migrateShadowsocksRemovedCiphers() error {
  744. var inbounds []model.Inbound
  745. if err := db.Where("protocol = ?", model.Shadowsocks).Find(&inbounds).Error; err != nil {
  746. return err
  747. }
  748. migrated := int64(0)
  749. for _, inbound := range inbounds {
  750. if strings.TrimSpace(inbound.Settings) == "" {
  751. continue
  752. }
  753. var settings map[string]any
  754. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  755. continue
  756. }
  757. changed := false
  758. if method, _ := settings["method"].(string); method != "" {
  759. if replacement, removed := model.ReplaceRemovedShadowsocksCipher(method); removed {
  760. settings["method"] = replacement
  761. changed = true
  762. }
  763. }
  764. if clients, ok := settings["clients"].([]any); ok {
  765. for i := range clients {
  766. cm, ok := clients[i].(map[string]any)
  767. if !ok {
  768. continue
  769. }
  770. method, _ := cm["method"].(string)
  771. if replacement, removed := model.ReplaceRemovedShadowsocksCipher(method); removed {
  772. cm["method"] = replacement
  773. clients[i] = cm
  774. changed = true
  775. }
  776. }
  777. }
  778. if !changed {
  779. continue
  780. }
  781. newSettings, err := json.MarshalIndent(settings, "", " ")
  782. if err != nil {
  783. log.Printf("migrateShadowsocksRemovedCiphers: skip inbound %d (marshal failed): %v", inbound.Id, err)
  784. continue
  785. }
  786. if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  787. Update("settings", string(newSettings)).Error; err != nil {
  788. return err
  789. }
  790. migrated++
  791. }
  792. if migrated > 0 {
  793. log.Printf("Rewrote removed shadowsocks cipher on %d inbound(s)", migrated)
  794. }
  795. return nil
  796. }
  797. // migrateVmessRemovedSecurities rewrites the vmess "none"/"zero" security
  798. // values that xray-core v26.7.11 removed to "auto" (what the core now treats
  799. // them as), on both the clients column and each vmess inbound's settings.
  800. func migrateVmessRemovedSecurities() error {
  801. res := db.Exec("UPDATE clients SET security = 'auto' WHERE security IN ('none', 'zero')")
  802. if res.Error != nil {
  803. log.Printf("Error migrating removed vmess security values on clients: %v", res.Error)
  804. return res.Error
  805. }
  806. if res.RowsAffected > 0 {
  807. log.Printf("Migrated %d client(s) off removed vmess security values", res.RowsAffected)
  808. }
  809. var inbounds []model.Inbound
  810. if err := db.Where("protocol = ?", model.VMESS).Find(&inbounds).Error; err != nil {
  811. return err
  812. }
  813. migrated := int64(0)
  814. for _, inbound := range inbounds {
  815. if strings.TrimSpace(inbound.Settings) == "" {
  816. continue
  817. }
  818. var settings map[string]any
  819. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  820. continue
  821. }
  822. clients, ok := settings["clients"].([]any)
  823. if !ok {
  824. continue
  825. }
  826. changed := false
  827. for i := range clients {
  828. cm, ok := clients[i].(map[string]any)
  829. if !ok {
  830. continue
  831. }
  832. if security, _ := cm["security"].(string); security == "none" || security == "zero" {
  833. cm["security"] = "auto"
  834. clients[i] = cm
  835. changed = true
  836. }
  837. }
  838. if !changed {
  839. continue
  840. }
  841. newSettings, err := json.MarshalIndent(settings, "", " ")
  842. if err != nil {
  843. log.Printf("migrateVmessRemovedSecurities: skip inbound %d (marshal failed): %v", inbound.Id, err)
  844. continue
  845. }
  846. if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  847. Update("settings", string(newSettings)).Error; err != nil {
  848. return err
  849. }
  850. migrated++
  851. }
  852. if migrated > 0 {
  853. log.Printf("Rewrote removed vmess security values on %d inbound(s)", migrated)
  854. }
  855. return nil
  856. }
  857. // migrateTgIDIndex creates an index on the clients.tg_id column so that
  858. // lookups by Telegram ID do not require a full table scan. The index tag
  859. // on the struct field already causes AutoMigrate to create it on new
  860. // installations; the explicit migration ensures existing databases get it.
  861. func migrateTgIDIndex() error {
  862. if db.Migrator().HasIndex(&model.ClientRecord{}, "idx_clients_tg_id") {
  863. return nil
  864. }
  865. return db.Migrator().CreateIndex(&model.ClientRecord{}, "TgID")
  866. }
  867. // normalizeInboundSubSortIndex lifts sub_sort_index values below the 1-based
  868. // minimum (rows written by builds that defaulted the column to 0, or by nodes
  869. // predating the field) so they cannot sort ahead of explicitly ranked inbounds.
  870. func normalizeInboundSubSortIndex() error {
  871. res := db.Exec("UPDATE inbounds SET sub_sort_index = 1 WHERE sub_sort_index < 1")
  872. if res.Error != nil {
  873. log.Printf("Error normalizing inbound sub_sort_index: %v", res.Error)
  874. return res.Error
  875. }
  876. if res.RowsAffected > 0 {
  877. log.Printf("Normalized sub_sort_index on %d inbound(s)", res.RowsAffected)
  878. }
  879. return nil
  880. }
  881. // repairOverflowedTrafficCounters heals traffic counters that historic
  882. // compounding bugs pushed past int64: on SQLite an overflowing INTEGER is
  883. // silently promoted to REAL, after which the column no longer scans into the
  884. // Go int64 field and every reader of the table fails (#5762). REAL cells are
  885. // cast back to INTEGER (SQLite caps the cast at math.MaxInt64), then values
  886. // are clamped into [0, TrafficMax] on both backends so the next delta cannot
  887. // overflow again.
  888. func repairOverflowedTrafficCounters() error {
  889. targets := []struct {
  890. table string
  891. columns []string
  892. }{
  893. {"client_traffics", []string{"up", "down"}},
  894. {"inbounds", []string{"up", "down"}},
  895. {"outbound_traffics", []string{"up", "down", "total"}},
  896. {"node_client_traffics", []string{"up", "down"}},
  897. }
  898. for _, target := range targets {
  899. for _, col := range target.columns {
  900. statements := []string{
  901. fmt.Sprintf("UPDATE %s SET %s = %d WHERE %s > %d", target.table, col, TrafficMax, col, TrafficMax),
  902. fmt.Sprintf("UPDATE %s SET %s = 0 WHERE %s < 0", target.table, col, col),
  903. }
  904. if !IsPostgres() {
  905. statements = append([]string{
  906. fmt.Sprintf("UPDATE %s SET %s = CAST(%s AS INTEGER) WHERE typeof(%s) = 'real'", target.table, col, col, col),
  907. }, statements...)
  908. }
  909. var repaired int64
  910. for _, statement := range statements {
  911. res := db.Exec(statement)
  912. if res.Error != nil {
  913. log.Printf("Error repairing %s.%s: %v", target.table, col, res.Error)
  914. return res.Error
  915. }
  916. repaired += res.RowsAffected
  917. }
  918. if repaired > 0 {
  919. log.Printf("Repaired %d overflowed %s.%s value(s)", repaired, target.table, col)
  920. }
  921. }
  922. }
  923. return nil
  924. }
  925. // dedupeInboundSettingsClients collapses duplicate same-email entries inside
  926. // every inbound's settings.clients array, keeping the first occurrence.
  927. // Retried or raced multi-node client adds on older builds appended the same
  928. // client several times (#5770), which the client lists then rendered as
  929. // phantom duplicates. Runs on every start (idempotent, writes only changed
  930. // rows) because a restored backup or a not-yet-upgraded node's snapshot can
  931. // reintroduce duplicates.
  932. func dedupeInboundSettingsClients() error {
  933. var inbounds []model.Inbound
  934. if err := db.Find(&inbounds).Error; err != nil {
  935. return err
  936. }
  937. repaired := int64(0)
  938. for _, inbound := range inbounds {
  939. if strings.TrimSpace(inbound.Settings) == "" {
  940. continue
  941. }
  942. var settings map[string]any
  943. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  944. continue
  945. }
  946. clients, _ := settings["clients"].([]any)
  947. if len(clients) < 2 {
  948. continue
  949. }
  950. seen := make(map[string]struct{}, len(clients))
  951. kept := make([]any, 0, len(clients))
  952. for _, c := range clients {
  953. if cm, ok := c.(map[string]any); ok {
  954. if email, _ := cm["email"].(string); email != "" {
  955. key := strings.ToLower(email)
  956. if _, dup := seen[key]; dup {
  957. continue
  958. }
  959. seen[key] = struct{}{}
  960. }
  961. }
  962. kept = append(kept, c)
  963. }
  964. if len(kept) == len(clients) {
  965. continue
  966. }
  967. settings["clients"] = kept
  968. newSettings, err := json.MarshalIndent(settings, "", " ")
  969. if err != nil {
  970. log.Printf("dedupeInboundSettingsClients: skip inbound %d (marshal failed): %v", inbound.Id, err)
  971. continue
  972. }
  973. if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  974. Update("settings", string(newSettings)).Error; err != nil {
  975. return err
  976. }
  977. repaired++
  978. }
  979. if repaired > 0 {
  980. log.Printf("Removed duplicate client entries from %d inbound(s)", repaired)
  981. }
  982. return nil
  983. }
  984. func isIgnorableDuplicateColumnErr(gdb *gorm.DB, err error, mdl any) bool {
  985. if err == nil {
  986. return false
  987. }
  988. errMsg := strings.ToLower(err.Error())
  989. const sqlitePrefix = "duplicate column name:"
  990. if _, after, ok := strings.Cut(errMsg, sqlitePrefix); ok {
  991. col := strings.TrimSpace(after)
  992. col = strings.Trim(col, "`\"[]")
  993. return col != "" && gdb != nil && gdb.Migrator().HasColumn(mdl, col)
  994. }
  995. if strings.Contains(errMsg, "already exists") && strings.Contains(errMsg, "column ") {
  996. if _, after, ok := strings.Cut(errMsg, "column \""); ok {
  997. rest := after
  998. if e := strings.Index(rest, "\""); e > 0 {
  999. col := rest[:e]
  1000. return col != "" && gdb != nil && gdb.Migrator().HasColumn(mdl, col)
  1001. }
  1002. }
  1003. }
  1004. return false
  1005. }
  1006. func initUser() error {
  1007. empty, err := isTableEmpty("users")
  1008. if err != nil {
  1009. log.Printf("Error checking if users table is empty: %v", err)
  1010. return err
  1011. }
  1012. if empty {
  1013. hashedPassword, err := crypto.HashPasswordAsBcrypt(defaultPassword)
  1014. if err != nil {
  1015. log.Printf("Error hashing default password: %v", err)
  1016. return err
  1017. }
  1018. user := &model.User{
  1019. Username: defaultUsername,
  1020. Password: hashedPassword,
  1021. }
  1022. return db.Create(user).Error
  1023. }
  1024. return nil
  1025. }
  1026. func runSeeders(isUsersEmpty bool) error {
  1027. empty, err := isTableEmpty("history_of_seeders")
  1028. if err != nil {
  1029. log.Printf("Error checking if users table is empty: %v", err)
  1030. return err
  1031. }
  1032. if empty && isUsersEmpty {
  1033. seeders := []string{"UserPasswordHash", "ClientsTable", "InboundClientsArrayFix", "InboundClientTgIdFix2", "InboundClientSubIdFix", "FreedomFinalRulesReverseFix", "FreedomFinalRulesPrivateEgressBlock", "InboundRealityFinalmaskTcpStrip", "ApiTokensHash", "LegacyProxySettingsCleanup", "WireguardPeersToClients", "MtprotoSecretsToClients", "NodeInboundsAdopted", "ResetIpLimitNoFail2ban"}
  1034. for _, name := range seeders {
  1035. if err := db.Create(&model.HistoryOfSeeders{SeederName: name}).Error; err != nil {
  1036. return err
  1037. }
  1038. }
  1039. return seedApiTokens()
  1040. }
  1041. var seedersHistory []string
  1042. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &seedersHistory).Error; err != nil {
  1043. log.Printf("Error fetching seeder history: %v", err)
  1044. return err
  1045. }
  1046. if !slices.Contains(seedersHistory, "UserPasswordHash") && !isUsersEmpty {
  1047. var users []model.User
  1048. if err := db.Find(&users).Error; err != nil {
  1049. log.Printf("Error fetching users for password migration: %v", err)
  1050. return err
  1051. }
  1052. for _, user := range users {
  1053. if crypto.IsHashed(user.Password) {
  1054. continue
  1055. }
  1056. hashedPassword, err := crypto.HashPasswordAsBcrypt(user.Password)
  1057. if err != nil {
  1058. log.Printf("Error hashing password for user '%s': %v", user.Username, err)
  1059. return err
  1060. }
  1061. if err := db.Model(&user).Update("password", hashedPassword).Error; err != nil {
  1062. log.Printf("Error updating password for user '%s': %v", user.Username, err)
  1063. return err
  1064. }
  1065. }
  1066. hashSeeder := &model.HistoryOfSeeders{
  1067. SeederName: "UserPasswordHash",
  1068. }
  1069. if err := db.Create(hashSeeder).Error; err != nil {
  1070. return err
  1071. }
  1072. }
  1073. if !slices.Contains(seedersHistory, "ApiTokensTable") {
  1074. if err := seedApiTokens(); err != nil {
  1075. return err
  1076. }
  1077. }
  1078. if !slices.Contains(seedersHistory, "ApiTokensHash") {
  1079. if err := hashExistingApiTokens(); err != nil {
  1080. return err
  1081. }
  1082. }
  1083. if !slices.Contains(seedersHistory, "ClientsTable") {
  1084. if err := seedClientsFromInboundJSON(); err != nil {
  1085. return err
  1086. }
  1087. }
  1088. if !slices.Contains(seedersHistory, "InboundClientsArrayFix") {
  1089. if err := normalizeInboundClientsArray(); err != nil {
  1090. return err
  1091. }
  1092. }
  1093. if !slices.Contains(seedersHistory, "InboundClientTgIdFix2") {
  1094. if err := normalizeInboundClientTgId(); err != nil {
  1095. return err
  1096. }
  1097. }
  1098. if !slices.Contains(seedersHistory, "InboundClientSubIdFix") {
  1099. if err := normalizeInboundClientSubId(); err != nil {
  1100. return err
  1101. }
  1102. }
  1103. if !slices.Contains(seedersHistory, "FreedomFinalRulesReverseFix") {
  1104. if err := normalizeFreedomFinalRules(); err != nil {
  1105. return err
  1106. }
  1107. }
  1108. if !slices.Contains(seedersHistory, "FreedomFinalRulesPrivateEgressBlock") {
  1109. if err := hardenFreedomFinalRules(); err != nil {
  1110. return err
  1111. }
  1112. }
  1113. if !slices.Contains(seedersHistory, "InboundRealityFinalmaskTcpStrip") {
  1114. if err := stripRealityFinalmaskTcp(); err != nil {
  1115. return err
  1116. }
  1117. }
  1118. if !slices.Contains(seedersHistory, "LegacyProxySettingsCleanup") {
  1119. if err := clearLegacyProxySettings(); err != nil {
  1120. return err
  1121. }
  1122. }
  1123. if !slices.Contains(seedersHistory, "NodeInboundsAdopted") {
  1124. if err := seedNodeInboundsAdopted(); err != nil {
  1125. return err
  1126. }
  1127. }
  1128. if err := seedHostsFromExternalProxy(); err != nil {
  1129. return err
  1130. }
  1131. if err := resetIpLimitsWithoutFail2ban(); err != nil {
  1132. return err
  1133. }
  1134. if err := seedWireguardPeersToClients(); err != nil {
  1135. return err
  1136. }
  1137. if err := backfillEmptyHostGroupIds(); err != nil {
  1138. return err
  1139. }
  1140. // Self-gated on the "MtprotoSecretsToClients" row.
  1141. if err := seedMtprotoSecretsToClients(); err != nil {
  1142. return err
  1143. }
  1144. // Self-gated on the "StripMtprotoInboundSecrets" row. Must run after the
  1145. // seeder above so legacy single-secret inbounds are first converted to a
  1146. // client (which preserves the secret) before the inbound-level copy is
  1147. // dropped from every mtproto inbound.
  1148. if err := stripMtprotoInboundSecrets(); err != nil {
  1149. return err
  1150. }
  1151. // Idempotent, not seeder-gated: bad values can re-enter via a restored
  1152. // backup, so re-check on every start.
  1153. return normalizeSettingPaths()
  1154. }
  1155. // seedNodeInboundsAdopted keeps the pre-existing reconcile behavior for nodes
  1156. // that were already syncing before the inbounds_adopted_at gate was introduced.
  1157. func seedNodeInboundsAdopted() error {
  1158. if err := db.Model(&model.Node{}).
  1159. Where("inbounds_adopted_at = 0").
  1160. Update("inbounds_adopted_at", time.Now().Unix()).Error; err != nil {
  1161. return err
  1162. }
  1163. return db.Create(&model.HistoryOfSeeders{SeederName: "NodeInboundsAdopted"}).Error
  1164. }
  1165. // backfillEmptyHostGroupIds is idempotent and not seeder-gated: builds that
  1166. // predate group ids on the inbound-import path (and restored backups) can
  1167. // re-introduce hosts rows with an empty group_id, and such rows render as a
  1168. // synthetic fallback_<id> group the update/delete API cannot address, so
  1169. // re-check on every start.
  1170. func backfillEmptyHostGroupIds() error {
  1171. var hosts []*model.Host
  1172. if err := db.Where("group_id = '' OR group_id IS NULL").Find(&hosts).Error; err != nil {
  1173. return err
  1174. }
  1175. if len(hosts) == 0 {
  1176. return nil
  1177. }
  1178. return db.Transaction(func(tx *gorm.DB) error {
  1179. for _, h := range hosts {
  1180. if err := tx.Model(h).Update("group_id", random.NumLower(16)).Error; err != nil {
  1181. return err
  1182. }
  1183. }
  1184. return nil
  1185. })
  1186. }
  1187. func resetIpLimitsWithoutFail2ban() error {
  1188. var history []string
  1189. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  1190. return err
  1191. }
  1192. if slices.Contains(history, "ResetIpLimitNoFail2ban") {
  1193. return nil
  1194. }
  1195. state, probeErr := fail2banEnforcementState()
  1196. if state == fail2banEnforcing {
  1197. return db.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
  1198. }
  1199. if state == fail2banUnknown {
  1200. log.Printf("ResetIpLimitNoFail2ban: fail2ban-client present but not runnable (%v); keeping configured IP limits, will retry next start", probeErr)
  1201. return nil
  1202. }
  1203. var inbounds []model.Inbound
  1204. if err := db.Find(&inbounds).Error; err != nil {
  1205. return err
  1206. }
  1207. return db.Transaction(func(tx *gorm.DB) error {
  1208. for _, inbound := range inbounds {
  1209. if strings.TrimSpace(inbound.Settings) == "" {
  1210. continue
  1211. }
  1212. var settings map[string]any
  1213. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1214. log.Printf("ResetIpLimitNoFail2ban: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1215. continue
  1216. }
  1217. clients, ok := settings["clients"].([]any)
  1218. if !ok {
  1219. continue
  1220. }
  1221. mutated := false
  1222. for i, raw := range clients {
  1223. obj, ok := raw.(map[string]any)
  1224. if !ok {
  1225. continue
  1226. }
  1227. v, present := obj["limitIp"]
  1228. if !present {
  1229. continue
  1230. }
  1231. if n, isNum := v.(float64); isNum && n == 0 {
  1232. continue
  1233. }
  1234. obj["limitIp"] = 0
  1235. clients[i] = obj
  1236. mutated = true
  1237. }
  1238. if !mutated {
  1239. continue
  1240. }
  1241. settings["clients"] = clients
  1242. newSettings, err := json.MarshalIndent(settings, "", " ")
  1243. if err != nil {
  1244. log.Printf("ResetIpLimitNoFail2ban: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1245. continue
  1246. }
  1247. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1248. Update("settings", string(newSettings)).Error; err != nil {
  1249. return err
  1250. }
  1251. }
  1252. if err := tx.Model(&model.ClientRecord{}).Where("limit_ip <> ?", 0).
  1253. Update("limit_ip", 0).Error; err != nil {
  1254. return err
  1255. }
  1256. return tx.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
  1257. })
  1258. }
  1259. type fail2banState int
  1260. const (
  1261. fail2banEnforcing fail2banState = iota
  1262. fail2banAbsent
  1263. fail2banUnknown
  1264. )
  1265. // fail2banEnforcementState separates "fail2ban is not installed" from "the probe
  1266. // itself failed", so a transient failure never drives an irreversible cleanup.
  1267. func fail2banEnforcementState() (fail2banState, error) {
  1268. if v, ok := os.LookupEnv("XUI_ENABLE_FAIL2BAN"); ok && v != "true" {
  1269. return fail2banAbsent, nil
  1270. }
  1271. if runtime.GOOS == "windows" {
  1272. return fail2banAbsent, nil
  1273. }
  1274. if _, err := exec.LookPath("fail2ban-client"); err != nil {
  1275. return fail2banAbsent, nil
  1276. }
  1277. if err := exec.CommandContext(context.Background(), "fail2ban-client", "-h").Run(); err != nil {
  1278. return fail2banUnknown, err
  1279. }
  1280. return fail2banEnforcing, nil
  1281. }
  1282. func clearLegacyProxySettings() error {
  1283. return db.Transaction(func(tx *gorm.DB) error {
  1284. if err := tx.Where("key IN ?", []string{"panelProxy", "tgBotProxy"}).
  1285. Delete(&model.Setting{}).Error; err != nil {
  1286. return err
  1287. }
  1288. return tx.Create(&model.HistoryOfSeeders{SeederName: "LegacyProxySettingsCleanup"}).Error
  1289. })
  1290. }
  1291. func normalizeSettingPaths() error {
  1292. pathKeys := []string{"webBasePath", "subPath", "subJsonPath", "subClashPath"}
  1293. var rows []model.Setting
  1294. if err := db.Where("key IN ?", pathKeys).Find(&rows).Error; err != nil {
  1295. return err
  1296. }
  1297. for _, row := range rows {
  1298. fixed := row.Value
  1299. if !strings.HasPrefix(fixed, "/") {
  1300. fixed = "/" + fixed
  1301. }
  1302. if !strings.HasSuffix(fixed, "/") {
  1303. fixed += "/"
  1304. }
  1305. if fixed == row.Value {
  1306. continue
  1307. }
  1308. if err := db.Model(&model.Setting{}).Where("id = ?", row.Id).
  1309. Update("value", fixed).Error; err != nil {
  1310. return err
  1311. }
  1312. }
  1313. return nil
  1314. }
  1315. func normalizeInboundClientTgId() error {
  1316. var inbounds []model.Inbound
  1317. if err := db.Find(&inbounds).Error; err != nil {
  1318. return err
  1319. }
  1320. return db.Transaction(func(tx *gorm.DB) error {
  1321. for _, inbound := range inbounds {
  1322. if strings.TrimSpace(inbound.Settings) == "" {
  1323. continue
  1324. }
  1325. var settings map[string]any
  1326. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1327. log.Printf("InboundClientTgIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1328. continue
  1329. }
  1330. clients, ok := settings["clients"].([]any)
  1331. if !ok {
  1332. continue
  1333. }
  1334. mutated := false
  1335. for i, raw := range clients {
  1336. obj, ok := raw.(map[string]any)
  1337. if !ok {
  1338. continue
  1339. }
  1340. tgRaw, present := obj["tgId"]
  1341. if !present {
  1342. continue
  1343. }
  1344. v, isFloat := tgRaw.(float64)
  1345. if isFloat && !math.IsNaN(v) && !math.IsInf(v, 0) && v == math.Trunc(v) {
  1346. continue
  1347. }
  1348. obj["tgId"] = int64(0)
  1349. if s, isStr := tgRaw.(string); isStr {
  1350. if id, err := strconv.ParseInt(strings.ReplaceAll(strings.TrimSpace(s), " ", ""), 10, 64); err == nil {
  1351. obj["tgId"] = id
  1352. }
  1353. }
  1354. clients[i] = obj
  1355. mutated = true
  1356. }
  1357. if !mutated {
  1358. continue
  1359. }
  1360. settings["clients"] = clients
  1361. newSettings, err := json.MarshalIndent(settings, "", " ")
  1362. if err != nil {
  1363. log.Printf("InboundClientTgIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1364. continue
  1365. }
  1366. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1367. Update("settings", string(newSettings)).Error; err != nil {
  1368. return err
  1369. }
  1370. }
  1371. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientTgIdFix2"}).Error
  1372. })
  1373. }
  1374. func normalizeInboundClientSubId() error {
  1375. var inbounds []model.Inbound
  1376. if err := db.Find(&inbounds).Error; err != nil {
  1377. return err
  1378. }
  1379. return db.Transaction(func(tx *gorm.DB) error {
  1380. for _, inbound := range inbounds {
  1381. if strings.TrimSpace(inbound.Settings) == "" {
  1382. continue
  1383. }
  1384. var settings map[string]any
  1385. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1386. log.Printf("InboundClientSubIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1387. continue
  1388. }
  1389. clients, ok := settings["clients"].([]any)
  1390. if !ok {
  1391. continue
  1392. }
  1393. mutated := false
  1394. for i, raw := range clients {
  1395. obj, ok := raw.(map[string]any)
  1396. if !ok {
  1397. continue
  1398. }
  1399. existing, _ := obj["subId"].(string)
  1400. if strings.TrimSpace(existing) != "" {
  1401. continue
  1402. }
  1403. obj["subId"] = random.NumLower(16)
  1404. clients[i] = obj
  1405. mutated = true
  1406. }
  1407. if !mutated {
  1408. continue
  1409. }
  1410. settings["clients"] = clients
  1411. newSettings, err := json.MarshalIndent(settings, "", " ")
  1412. if err != nil {
  1413. log.Printf("InboundClientSubIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1414. continue
  1415. }
  1416. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1417. Update("settings", string(newSettings)).Error; err != nil {
  1418. return err
  1419. }
  1420. }
  1421. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientSubIdFix"}).Error
  1422. })
  1423. }
  1424. func normalizeInboundClientsArray() error {
  1425. var inbounds []model.Inbound
  1426. if err := db.Find(&inbounds).Error; err != nil {
  1427. return err
  1428. }
  1429. return db.Transaction(func(tx *gorm.DB) error {
  1430. for _, inbound := range inbounds {
  1431. if strings.TrimSpace(inbound.Settings) == "" {
  1432. continue
  1433. }
  1434. var settings map[string]any
  1435. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1436. log.Printf("InboundClientsArrayFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1437. continue
  1438. }
  1439. raw, exists := settings["clients"]
  1440. if !exists || raw != nil {
  1441. continue
  1442. }
  1443. settings["clients"] = []any{}
  1444. newSettings, err := json.MarshalIndent(settings, "", " ")
  1445. if err != nil {
  1446. log.Printf("InboundClientsArrayFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1447. continue
  1448. }
  1449. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1450. Update("settings", string(newSettings)).Error; err != nil {
  1451. return err
  1452. }
  1453. }
  1454. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientsArrayFix"}).Error
  1455. })
  1456. }
  1457. func normalizeFreedomFinalRules() error {
  1458. var setting model.Setting
  1459. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  1460. if errors.Is(err, gorm.ErrRecordNotFound) {
  1461. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  1462. }
  1463. if err != nil {
  1464. return err
  1465. }
  1466. updated, changed, rErr := rewriteFreedomFinalRules(setting.Value)
  1467. if rErr != nil {
  1468. log.Printf("FreedomFinalRulesReverseFix: skip (invalid xrayTemplateConfig json): %v", rErr)
  1469. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  1470. }
  1471. return db.Transaction(func(tx *gorm.DB) error {
  1472. if changed {
  1473. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  1474. Update("value", updated).Error; err != nil {
  1475. return err
  1476. }
  1477. }
  1478. return tx.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  1479. })
  1480. }
  1481. func rewriteFreedomFinalRules(raw string) (string, bool, error) {
  1482. if strings.TrimSpace(raw) == "" {
  1483. return raw, false, nil
  1484. }
  1485. var cfg map[string]any
  1486. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  1487. return raw, false, err
  1488. }
  1489. outbounds, ok := cfg["outbounds"].([]any)
  1490. if !ok {
  1491. return raw, false, nil
  1492. }
  1493. changed := false
  1494. for _, ob := range outbounds {
  1495. obj, ok := ob.(map[string]any)
  1496. if !ok {
  1497. continue
  1498. }
  1499. if proto, _ := obj["protocol"].(string); proto != "freedom" {
  1500. continue
  1501. }
  1502. settings, ok := obj["settings"].(map[string]any)
  1503. if !ok {
  1504. continue
  1505. }
  1506. if !isLegacyPrivateOnlyFinalRules(settings["finalRules"]) {
  1507. continue
  1508. }
  1509. settings["finalRules"] = []any{map[string]any{"action": "allow"}}
  1510. changed = true
  1511. }
  1512. if !changed {
  1513. return raw, false, nil
  1514. }
  1515. out, err := json.MarshalIndent(cfg, "", " ")
  1516. if err != nil {
  1517. return raw, false, err
  1518. }
  1519. return string(out), true, nil
  1520. }
  1521. func isLegacyPrivateOnlyFinalRules(v any) bool {
  1522. rules, ok := v.([]any)
  1523. if !ok || len(rules) != 1 {
  1524. return false
  1525. }
  1526. rule, ok := rules[0].(map[string]any)
  1527. if !ok {
  1528. return false
  1529. }
  1530. if action, _ := rule["action"].(string); action != "allow" {
  1531. return false
  1532. }
  1533. ips, ok := rule["ip"].([]any)
  1534. if !ok || len(ips) != 1 {
  1535. return false
  1536. }
  1537. if s, _ := ips[0].(string); s != "geoip:private" {
  1538. return false
  1539. }
  1540. for k := range rule {
  1541. if k != "action" && k != "ip" {
  1542. return false
  1543. }
  1544. }
  1545. return true
  1546. }
  1547. func isUnrestrictedFreedomFinalRules(v any, present bool) bool {
  1548. if !present || v == nil {
  1549. return true
  1550. }
  1551. rules, ok := v.([]any)
  1552. return ok && len(rules) == 0
  1553. }
  1554. func hardenFreedomFinalRules() error {
  1555. var setting model.Setting
  1556. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  1557. if errors.Is(err, gorm.ErrRecordNotFound) {
  1558. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesPrivateEgressBlock"}).Error
  1559. }
  1560. if err != nil {
  1561. return err
  1562. }
  1563. updated, changed, rErr := rewriteFreedomFinalRulesPrivateEgress(setting.Value)
  1564. if rErr != nil {
  1565. log.Printf("FreedomFinalRulesPrivateEgressBlock: skip (invalid xrayTemplateConfig json): %v", rErr)
  1566. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesPrivateEgressBlock"}).Error
  1567. }
  1568. return db.Transaction(func(tx *gorm.DB) error {
  1569. if changed {
  1570. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  1571. Update("value", updated).Error; err != nil {
  1572. return err
  1573. }
  1574. }
  1575. return tx.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesPrivateEgressBlock"}).Error
  1576. })
  1577. }
  1578. func rewriteFreedomFinalRulesPrivateEgress(raw string) (string, bool, error) {
  1579. if strings.TrimSpace(raw) == "" {
  1580. return raw, false, nil
  1581. }
  1582. var cfg map[string]any
  1583. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  1584. return raw, false, err
  1585. }
  1586. outbounds, ok := cfg["outbounds"].([]any)
  1587. if !ok {
  1588. return raw, false, nil
  1589. }
  1590. changed := false
  1591. for _, ob := range outbounds {
  1592. obj, ok := ob.(map[string]any)
  1593. if !ok {
  1594. continue
  1595. }
  1596. if proto, _ := obj["protocol"].(string); proto != "freedom" {
  1597. continue
  1598. }
  1599. settings, ok := obj["settings"].(map[string]any)
  1600. if !ok {
  1601. continue
  1602. }
  1603. finalRules, present := settings["finalRules"]
  1604. if !isUnrestrictedFreedomFinalRules(finalRules, present) &&
  1605. !isAllowOnlyFinalRules(finalRules) &&
  1606. !isLegacyPrivateOnlyFinalRules(finalRules) {
  1607. continue
  1608. }
  1609. settings["finalRules"] = []any{
  1610. map[string]any{"action": "block", "ip": []any{"geoip:private"}},
  1611. map[string]any{"action": "allow"},
  1612. }
  1613. changed = true
  1614. }
  1615. if !changed {
  1616. return raw, false, nil
  1617. }
  1618. out, err := json.MarshalIndent(cfg, "", " ")
  1619. if err != nil {
  1620. return raw, false, err
  1621. }
  1622. return string(out), true, nil
  1623. }
  1624. func stripRealityFinalmaskTcp() error {
  1625. var inbounds []model.Inbound
  1626. if err := db.Find(&inbounds).Error; err != nil {
  1627. return err
  1628. }
  1629. return db.Transaction(func(tx *gorm.DB) error {
  1630. for i := range inbounds {
  1631. updated, changed := stripRealityFinalmaskTcpFromStream(inbounds[i].StreamSettings)
  1632. if !changed {
  1633. continue
  1634. }
  1635. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbounds[i].Id).
  1636. Update("stream_settings", updated).Error; err != nil {
  1637. return err
  1638. }
  1639. log.Printf("InboundRealityFinalmaskTcpStrip: removed finalmask.tcp from REALITY inbound %d (%s)", inbounds[i].Id, inbounds[i].Tag)
  1640. }
  1641. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundRealityFinalmaskTcpStrip"}).Error
  1642. })
  1643. }
  1644. func stripRealityFinalmaskTcpFromStream(raw string) (string, bool) {
  1645. if strings.TrimSpace(raw) == "" {
  1646. return raw, false
  1647. }
  1648. var stream map[string]any
  1649. if err := json.Unmarshal([]byte(raw), &stream); err != nil {
  1650. return raw, false
  1651. }
  1652. if sec, _ := stream["security"].(string); sec != "reality" {
  1653. return raw, false
  1654. }
  1655. finalmask, ok := stream["finalmask"].(map[string]any)
  1656. if !ok {
  1657. return raw, false
  1658. }
  1659. if tcp, _ := finalmask["tcp"].([]any); len(tcp) == 0 {
  1660. return raw, false
  1661. }
  1662. delete(finalmask, "tcp")
  1663. if len(finalmask) == 0 {
  1664. delete(stream, "finalmask")
  1665. }
  1666. out, err := json.Marshal(stream)
  1667. if err != nil {
  1668. return raw, false
  1669. }
  1670. return string(out), true
  1671. }
  1672. func isAllowOnlyFinalRules(v any) bool {
  1673. rules, ok := v.([]any)
  1674. if !ok || len(rules) != 1 {
  1675. return false
  1676. }
  1677. rule, ok := rules[0].(map[string]any)
  1678. if !ok {
  1679. return false
  1680. }
  1681. if action, _ := rule["action"].(string); action != "allow" {
  1682. return false
  1683. }
  1684. for k := range rule {
  1685. if k != "action" {
  1686. return false
  1687. }
  1688. }
  1689. return true
  1690. }
  1691. func normalizeClientJSONFields(obj map[string]any) {
  1692. normalizeInt := func(key string) {
  1693. raw, exists := obj[key]
  1694. if !exists {
  1695. return
  1696. }
  1697. s, ok := raw.(string)
  1698. if !ok {
  1699. return
  1700. }
  1701. trimmed := strings.ReplaceAll(strings.TrimSpace(s), " ", "")
  1702. if trimmed == "" {
  1703. delete(obj, key)
  1704. return
  1705. }
  1706. if n, err := strconv.ParseInt(trimmed, 10, 64); err == nil {
  1707. obj[key] = n
  1708. } else {
  1709. delete(obj, key)
  1710. }
  1711. }
  1712. for _, k := range []string{"tgId", "limitIp", "totalGB", "expiryTime", "reset", "created_at", "updated_at"} {
  1713. normalizeInt(k)
  1714. }
  1715. }
  1716. func seedClientsFromInboundJSON() error {
  1717. var inbounds []model.Inbound
  1718. if err := db.Find(&inbounds).Error; err != nil {
  1719. return err
  1720. }
  1721. return db.Transaction(func(tx *gorm.DB) error {
  1722. byEmail := map[string]*model.ClientRecord{}
  1723. var existing []model.ClientRecord
  1724. if err := tx.Find(&existing).Error; err != nil {
  1725. return err
  1726. }
  1727. for i := range existing {
  1728. byEmail[existing[i].Email] = &existing[i]
  1729. }
  1730. for _, inbound := range inbounds {
  1731. if strings.TrimSpace(inbound.Settings) == "" {
  1732. continue
  1733. }
  1734. var settings map[string]any
  1735. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1736. log.Printf("ClientsTable seed: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1737. continue
  1738. }
  1739. rawList, ok := settings["clients"].([]any)
  1740. if !ok {
  1741. continue
  1742. }
  1743. for _, raw := range rawList {
  1744. obj, ok := raw.(map[string]any)
  1745. if !ok {
  1746. continue
  1747. }
  1748. normalizeClientJSONFields(obj)
  1749. blob, err := json.Marshal(obj)
  1750. if err != nil {
  1751. continue
  1752. }
  1753. var c model.Client
  1754. if err := json.Unmarshal(blob, &c); err != nil {
  1755. log.Printf("ClientsTable seed: skip client in inbound %d (unmarshal failed): %v; payload=%s",
  1756. inbound.Id, err, string(blob))
  1757. continue
  1758. }
  1759. email := strings.TrimSpace(c.Email)
  1760. if email == "" {
  1761. continue
  1762. }
  1763. incoming := c.ToRecord()
  1764. row, dup := byEmail[email]
  1765. if !dup {
  1766. if err := tx.Create(incoming).Error; err != nil {
  1767. return err
  1768. }
  1769. byEmail[email] = incoming
  1770. row = incoming
  1771. } else {
  1772. conflicts := model.MergeClientRecord(row, incoming)
  1773. for _, x := range conflicts {
  1774. log.Printf("client merge: email=%s conflict on %s old=%v new=%v kept=%v",
  1775. email, x.Field, x.Old, x.New, x.Kept)
  1776. }
  1777. if err := tx.Save(row).Error; err != nil {
  1778. return err
  1779. }
  1780. }
  1781. link := model.ClientInbound{
  1782. ClientId: row.Id,
  1783. InboundId: inbound.Id,
  1784. FlowOverride: c.Flow,
  1785. }
  1786. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  1787. FirstOrCreate(&link).Error; err != nil {
  1788. return err
  1789. }
  1790. }
  1791. }
  1792. return tx.Create(&model.HistoryOfSeeders{SeederName: "ClientsTable"}).Error
  1793. })
  1794. }
  1795. func seedApiTokens() error {
  1796. empty, err := isTableEmpty("api_tokens")
  1797. if err != nil {
  1798. return err
  1799. }
  1800. if empty {
  1801. var legacy model.Setting
  1802. err := db.Model(model.Setting{}).Where("key = ?", "apiToken").First(&legacy).Error
  1803. if err == nil && legacy.Value != "" {
  1804. row := &model.ApiToken{
  1805. Name: "default",
  1806. Token: legacy.Value,
  1807. Enabled: true,
  1808. }
  1809. if err := db.Create(row).Error; err != nil {
  1810. log.Printf("Error migrating legacy apiToken: %v", err)
  1811. return err
  1812. }
  1813. }
  1814. }
  1815. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensTable"}).Error
  1816. }
  1817. func hashExistingApiTokens() error {
  1818. var rows []*model.ApiToken
  1819. if err := db.Find(&rows).Error; err != nil {
  1820. return err
  1821. }
  1822. for _, r := range rows {
  1823. if crypto.IsSHA256Hex(r.Token) {
  1824. continue
  1825. }
  1826. hashed := crypto.HashTokenSHA256(r.Token)
  1827. if err := db.Model(model.ApiToken{}).Where("id = ?", r.Id).Update("token", hashed).Error; err != nil {
  1828. log.Printf("Error hashing api token %d: %v", r.Id, err)
  1829. return err
  1830. }
  1831. }
  1832. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensHash"}).Error
  1833. }
  1834. func isTableEmpty(tableName string) (bool, error) {
  1835. var count int64
  1836. err := db.Table(tableName).Count(&count).Error
  1837. return count == 0, err
  1838. }
  1839. func InitDB(dbPath string) error {
  1840. var gormLogger logger.Interface
  1841. if config.IsDebug() {
  1842. gormLogger = logger.New(
  1843. log.New(os.Stdout, "\r\n", log.LstdFlags),
  1844. logger.Config{
  1845. SlowThreshold: time.Second,
  1846. LogLevel: logger.Info,
  1847. IgnoreRecordNotFoundError: true,
  1848. Colorful: true,
  1849. },
  1850. )
  1851. } else {
  1852. gormLogger = logger.Discard
  1853. }
  1854. c := &gorm.Config{Logger: gormLogger, DisableForeignKeyConstraintWhenMigrating: true}
  1855. var err error
  1856. switch config.GetDBKind() {
  1857. case "postgres":
  1858. dsn := config.GetDBDSN()
  1859. if dsn == "" {
  1860. return errors.New("XUI_DB_TYPE=postgres but XUI_DB_DSN is empty")
  1861. }
  1862. db, err = openPostgresWithRetry(dsn, c)
  1863. if err != nil {
  1864. return err
  1865. }
  1866. default:
  1867. dir := path.Dir(dbPath)
  1868. if err = os.MkdirAll(dir, 0o755); err != nil {
  1869. return err
  1870. }
  1871. if err = cleanupSQLiteBackupDirs(filepath.Dir(dbPath)); err != nil {
  1872. log.Printf("clean SQLite backup directories: %v", err)
  1873. }
  1874. sync := sqliteSynchronous()
  1875. journal := sqliteJournalMode()
  1876. dsn := dbPath + "?_journal_mode=" + journal + "&_busy_timeout=10000&_synchronous=" + sync + "&_txlock=immediate"
  1877. db, err = gorm.Open(sqlite.Open(dsn), c)
  1878. if err != nil {
  1879. return err
  1880. }
  1881. sqlDB, err := db.DB()
  1882. if err != nil {
  1883. return err
  1884. }
  1885. pragmas := []string{
  1886. "PRAGMA journal_mode=" + journal,
  1887. "PRAGMA busy_timeout=10000",
  1888. "PRAGMA synchronous=" + sync,
  1889. fmt.Sprintf("PRAGMA cache_size=-%d", envInt("XUI_DB_CACHE_MB", 32)*1024),
  1890. fmt.Sprintf("PRAGMA mmap_size=%d", int64(envInt("XUI_DB_MMAP_MB", 256))*1024*1024),
  1891. "PRAGMA temp_store=MEMORY",
  1892. }
  1893. for _, p := range pragmas {
  1894. if _, err := sqlDB.ExecContext(context.Background(), p); err != nil {
  1895. return err
  1896. }
  1897. }
  1898. }
  1899. sqlDB, err := db.DB()
  1900. if err != nil {
  1901. return err
  1902. }
  1903. var maxOpen, maxIdle int
  1904. switch config.GetDBKind() {
  1905. case "postgres":
  1906. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 25)
  1907. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 25)
  1908. default:
  1909. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 8)
  1910. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 4)
  1911. }
  1912. sqlDB.SetMaxOpenConns(maxOpen)
  1913. sqlDB.SetMaxIdleConns(maxIdle)
  1914. sqlDB.SetConnMaxLifetime(time.Hour)
  1915. sqlDB.SetConnMaxIdleTime(30 * time.Minute)
  1916. if err := initModels(); err != nil {
  1917. return err
  1918. }
  1919. isUsersEmpty, err := isTableEmpty("users")
  1920. if err != nil {
  1921. return err
  1922. }
  1923. if err := initUser(); err != nil {
  1924. return err
  1925. }
  1926. return runSeeders(isUsersEmpty)
  1927. }
  1928. func normalizeApiTokenCreatedAtSeconds() error {
  1929. return db.Model(&model.ApiToken{}).
  1930. Where("created_at >= ?", model.ApiTokenUnixMillisecondsThreshold).
  1931. UpdateColumn("created_at", gorm.Expr("created_at / ?", 1000)).Error
  1932. }
  1933. // openPostgresWithRetry retries the initial PostgreSQL connection with
  1934. // backoff so a database that starts slower than the panel (or drops out
  1935. // briefly) does not immediately kill the process and trip systemd's
  1936. // restart loop. Every failed attempt logs the real driver error, which
  1937. // used to be buried behind a generic startup failure.
  1938. func openPostgresWithRetry(dsn string, c *gorm.Config) (*gorm.DB, error) {
  1939. delays := []time.Duration{0, 2 * time.Second, 5 * time.Second, 10 * time.Second, 20 * time.Second, 30 * time.Second}
  1940. var lastErr error
  1941. for i, delay := range delays {
  1942. if delay > 0 {
  1943. time.Sleep(delay)
  1944. }
  1945. conn, err := gorm.Open(postgres.Open(dsn), c)
  1946. if err == nil {
  1947. if i > 0 {
  1948. log.Printf("postgres connection established on attempt %d/%d", i+1, len(delays))
  1949. }
  1950. return conn, nil
  1951. }
  1952. lastErr = err
  1953. log.Printf("postgres connection attempt %d/%d failed: %v", i+1, len(delays), err)
  1954. }
  1955. return nil, fmt.Errorf("postgres unreachable after %d attempts: %w", len(delays), lastErr)
  1956. }
  1957. func sqliteJournalMode() string {
  1958. switch strings.ToUpper(strings.TrimSpace(os.Getenv("XUI_DB_JOURNAL_MODE"))) {
  1959. case "DELETE":
  1960. return "DELETE"
  1961. default:
  1962. return "WAL"
  1963. }
  1964. }
  1965. func backupSQLiteStepPages() int {
  1966. if sqliteJournalMode() == "DELETE" {
  1967. return 128
  1968. }
  1969. return -1
  1970. }
  1971. func cleanupSQLiteBackupDirs(dir string) error {
  1972. entries, err := os.ReadDir(dir)
  1973. if errors.Is(err, os.ErrNotExist) {
  1974. return nil
  1975. }
  1976. if err != nil {
  1977. return err
  1978. }
  1979. for _, entry := range entries {
  1980. if entry.IsDir() && strings.HasPrefix(entry.Name(), sqliteBackupDirPrefix) {
  1981. if err := os.RemoveAll(filepath.Join(dir, entry.Name())); err != nil {
  1982. return err
  1983. }
  1984. }
  1985. }
  1986. return nil
  1987. }
  1988. func sqliteSynchronous() string {
  1989. switch strings.ToUpper(strings.TrimSpace(os.Getenv("XUI_DB_SYNCHRONOUS"))) {
  1990. case "OFF":
  1991. return "OFF"
  1992. case "NORMAL":
  1993. return "NORMAL"
  1994. case "EXTRA":
  1995. return "EXTRA"
  1996. default:
  1997. return "FULL"
  1998. }
  1999. }
  2000. func envInt(key string, def int) int {
  2001. v := strings.TrimSpace(os.Getenv(key))
  2002. if v == "" {
  2003. return def
  2004. }
  2005. n, err := strconv.Atoi(v)
  2006. if err != nil || n <= 0 {
  2007. return def
  2008. }
  2009. return n
  2010. }
  2011. func CloseDB() error {
  2012. if db != nil {
  2013. sqlDB, err := db.DB()
  2014. if err != nil {
  2015. return err
  2016. }
  2017. return sqlDB.Close()
  2018. }
  2019. return nil
  2020. }
  2021. func GetDB() *gorm.DB {
  2022. return db
  2023. }
  2024. func IsNotFound(err error) bool {
  2025. return errors.Is(err, gorm.ErrRecordNotFound)
  2026. }
  2027. func IsSQLiteDB(file io.ReaderAt) (bool, error) {
  2028. signature := []byte("SQLite format 3\x00")
  2029. buf := make([]byte, len(signature))
  2030. _, err := file.ReadAt(buf, 0)
  2031. if err != nil {
  2032. return false, err
  2033. }
  2034. return bytes.Equal(buf, signature), nil
  2035. }
  2036. func BackupSQLite(dstPath string) (err error) {
  2037. if IsPostgres() {
  2038. return errors.New("sqlite backup is unavailable for PostgreSQL")
  2039. }
  2040. if db == nil {
  2041. return errors.New("database is not initialized")
  2042. }
  2043. if _, err := os.Lstat(dstPath); err == nil {
  2044. return fmt.Errorf("sqlite backup destination already exists: %s", dstPath)
  2045. } else if !errors.Is(err, os.ErrNotExist) {
  2046. return err
  2047. }
  2048. defer func() {
  2049. if err != nil {
  2050. _ = os.Remove(dstPath)
  2051. }
  2052. }()
  2053. ctx, cancel := context.WithTimeout(context.Background(), backupSQLiteTimeout)
  2054. defer cancel()
  2055. sourceDB, err := db.DB()
  2056. if err != nil {
  2057. return err
  2058. }
  2059. sourceConn, err := sourceDB.Conn(ctx)
  2060. if err != nil {
  2061. return err
  2062. }
  2063. defer sourceConn.Close()
  2064. destinationDB, err := sql.Open("sqlite3", dstPath)
  2065. if err != nil {
  2066. return err
  2067. }
  2068. defer destinationDB.Close()
  2069. destinationConn, err := destinationDB.Conn(ctx)
  2070. if err != nil {
  2071. return err
  2072. }
  2073. defer destinationConn.Close()
  2074. return sourceConn.Raw(func(sourceDriver any) error {
  2075. source, ok := sourceDriver.(*sqlite3.SQLiteConn)
  2076. if !ok {
  2077. return fmt.Errorf("unexpected SQLite source connection type %T", sourceDriver)
  2078. }
  2079. return destinationConn.Raw(func(destinationDriver any) error {
  2080. destination, ok := destinationDriver.(*sqlite3.SQLiteConn)
  2081. if !ok {
  2082. return fmt.Errorf("unexpected SQLite destination connection type %T", destinationDriver)
  2083. }
  2084. backup, err := destination.Backup("main", source, "main")
  2085. if err != nil {
  2086. return err
  2087. }
  2088. finished := false
  2089. defer func() {
  2090. if !finished {
  2091. _ = backup.Finish()
  2092. }
  2093. }()
  2094. for {
  2095. done, err := backup.Step(backupSQLiteStepPages())
  2096. if err != nil {
  2097. return err
  2098. }
  2099. if done {
  2100. finished = true
  2101. return backup.Finish()
  2102. }
  2103. select {
  2104. case <-ctx.Done():
  2105. return ctx.Err()
  2106. case <-time.After(10 * time.Millisecond):
  2107. }
  2108. }
  2109. })
  2110. })
  2111. }
  2112. func ValidateSQLiteDB(dbPath string) error {
  2113. if _, err := os.Stat(dbPath); err != nil {
  2114. return err
  2115. }
  2116. gdb, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{Logger: logger.Discard})
  2117. if err != nil {
  2118. return err
  2119. }
  2120. sqlDB, err := gdb.DB()
  2121. if err != nil {
  2122. return err
  2123. }
  2124. defer sqlDB.Close()
  2125. var res string
  2126. if err := gdb.Raw("PRAGMA integrity_check;").Scan(&res).Error; err != nil {
  2127. return err
  2128. }
  2129. if res != "ok" {
  2130. return errors.New("sqlite integrity check failed: " + res)
  2131. }
  2132. return nil
  2133. }