db.go 64 KB

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