db.go 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037
  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. &model.SubBalancer{},
  78. }
  79. }
  80. func migrateClientTrafficLastSubFetchColumn() error {
  81. migrator := db.Migrator()
  82. if !migrator.HasTable(&xray.ClientTraffic{}) || migrator.HasColumn(&xray.ClientTraffic{}, "last_sub_fetch") {
  83. return nil
  84. }
  85. return migrator.AddColumn(&xray.ClientTraffic{}, "LastSubFetch")
  86. }
  87. func migrateOutboundSubscriptionUserAgentColumn() error {
  88. migrator := db.Migrator()
  89. if !migrator.HasTable(&model.OutboundSubscription{}) || migrator.HasColumn(&model.OutboundSubscription{}, "user_agent") {
  90. return nil
  91. }
  92. return migrator.AddColumn(&model.OutboundSubscription{}, "UserAgent")
  93. }
  94. func migrateInboundExcludeFromSubColumn() error {
  95. migrator := db.Migrator()
  96. if !migrator.HasTable(&model.Inbound{}) || migrator.HasColumn(&model.Inbound{}, "exclude_from_sub") {
  97. return nil
  98. }
  99. return migrator.AddColumn(&model.Inbound{}, "ExcludeFromSub")
  100. }
  101. func initModels() error {
  102. if err := migrateClientTrafficLastSubFetchColumn(); err != nil {
  103. return err
  104. }
  105. if err := migrateOutboundSubscriptionUserAgentColumn(); err != nil {
  106. return err
  107. }
  108. if err := migrateInboundExcludeFromSubColumn(); err != nil {
  109. return err
  110. }
  111. models := allModels()
  112. for _, mdl := range models {
  113. if IsPostgres() && postgresModelSettled(mdl) {
  114. continue
  115. }
  116. if err := db.AutoMigrate(mdl); err != nil {
  117. if isIgnorableDuplicateColumnErr(db, err, mdl) {
  118. log.Printf("Ignoring duplicate column during auto migration for %T: %v", mdl, err)
  119. continue
  120. }
  121. log.Printf("Error auto migrating model: %v", err)
  122. return err
  123. }
  124. }
  125. if err := dropLegacyInboundPortUnique(); err != nil {
  126. return err
  127. }
  128. if err := migrateHostVerifyPeerCertByNameColumn(); err != nil {
  129. return err
  130. }
  131. if err := normalizeApiTokenCreatedAtSeconds(); err != nil {
  132. return err
  133. }
  134. if err := migrateApiTokenScopeAndExpiry(); err != nil {
  135. return err
  136. }
  137. if err := dropLegacyForeignKeys(); err != nil {
  138. return err
  139. }
  140. if err := pruneOrphanedClientInbounds(); err != nil {
  141. return err
  142. }
  143. if err := pruneOrphanedHosts(); err != nil {
  144. return err
  145. }
  146. if err := normalizeInboundSubSortIndex(); err != nil {
  147. return err
  148. }
  149. if err := normalizeClientExternalLinkEnable(); err != nil {
  150. return err
  151. }
  152. if err := normalizeClientExternalLinkTimestamps(); err != nil {
  153. return err
  154. }
  155. if err := repairOverflowedTrafficCounters(); err != nil {
  156. return err
  157. }
  158. if err := dedupeInboundSettingsClients(); err != nil {
  159. return err
  160. }
  161. if err := migrateLegacySocksInboundsToMixed(); err != nil {
  162. return err
  163. }
  164. if err := migrateShadowsocksRemovedCiphers(); err != nil {
  165. return err
  166. }
  167. if err := migrateVmessRemovedSecurities(); err != nil {
  168. return err
  169. }
  170. if err := migrateTgIDIndex(); err != nil {
  171. return err
  172. }
  173. if err := migrateClientTrafficResetColumns(); err != nil {
  174. return err
  175. }
  176. if err := migrateClientResetWeekdayColumns(); err != nil {
  177. return err
  178. }
  179. if err := migrateSyncOrphanColumns(); err != nil {
  180. return err
  181. }
  182. if err := migrateClientEmailLowerIndex(); err != nil {
  183. return err
  184. }
  185. if IsPostgres() {
  186. if err := resyncPostgresSequences(db, models); err != nil {
  187. log.Printf("Error resyncing postgres sequences: %v", err)
  188. return err
  189. }
  190. }
  191. return nil
  192. }
  193. func postgresModelSettled(mdl any) bool {
  194. migrator := db.Migrator()
  195. if !migrator.HasTable(mdl) {
  196. return false
  197. }
  198. stmt := &gorm.Statement{DB: db}
  199. if err := stmt.Parse(mdl); err != nil || stmt.Schema == nil {
  200. return false
  201. }
  202. for _, dbName := range stmt.Schema.DBNames {
  203. if !migrator.HasColumn(mdl, dbName) {
  204. return false
  205. }
  206. }
  207. for _, idx := range stmt.Schema.ParseIndexes() {
  208. if !migrator.HasIndex(mdl, idx.Name) {
  209. return false
  210. }
  211. }
  212. return true
  213. }
  214. func dropLegacyForeignKeys() error {
  215. if !IsPostgres() {
  216. return nil
  217. }
  218. if err := db.Exec("ALTER TABLE client_traffics DROP CONSTRAINT IF EXISTS fk_inbounds_client_stats").Error; err != nil {
  219. log.Printf("Error dropping legacy foreign key fk_inbounds_client_stats: %v", err)
  220. return err
  221. }
  222. return nil
  223. }
  224. type sqliteIndexListRow struct {
  225. Name string `gorm:"column:name"`
  226. Unique int `gorm:"column:unique"`
  227. Origin string `gorm:"column:origin"`
  228. }
  229. func sqliteUniquePortIndexes() (autoIndexes, explicitIndexes []string, err error) {
  230. var list []sqliteIndexListRow
  231. if err = db.Raw(`PRAGMA index_list('inbounds')`).Scan(&list).Error; err != nil {
  232. return nil, nil, err
  233. }
  234. for _, idx := range list {
  235. if idx.Unique != 1 {
  236. continue
  237. }
  238. var cols []struct {
  239. Name string `gorm:"column:name"`
  240. }
  241. if err = db.Raw(`PRAGMA index_info("` + idx.Name + `")`).Scan(&cols).Error; err != nil {
  242. return nil, nil, err
  243. }
  244. if len(cols) != 1 || cols[0].Name != "port" {
  245. continue
  246. }
  247. if idx.Origin == "c" {
  248. explicitIndexes = append(explicitIndexes, idx.Name)
  249. } else {
  250. autoIndexes = append(autoIndexes, idx.Name)
  251. }
  252. }
  253. return autoIndexes, explicitIndexes, nil
  254. }
  255. // dropLegacyInboundPortUnique removes the pre-multi-node UNIQUE on inbounds.port,
  256. // which AutoMigrate never drops and which blocks cross-node port reuse on old SQLite DBs.
  257. func dropLegacyInboundPortUnique() error {
  258. if IsPostgres() {
  259. return nil
  260. }
  261. autoIndexes, explicitIndexes, err := sqliteUniquePortIndexes()
  262. if err != nil {
  263. return err
  264. }
  265. for _, name := range explicitIndexes {
  266. if err := db.Exec(`DROP INDEX IF EXISTS "` + name + `"`).Error; err != nil {
  267. return err
  268. }
  269. }
  270. if len(autoIndexes) == 0 {
  271. return nil
  272. }
  273. log.Printf("Rebuilding inbounds table to drop the legacy UNIQUE constraint on port")
  274. return rebuildInboundsWithoutInlineUniquePort()
  275. }
  276. func sqliteTableColumns(tx *gorm.DB, table string) ([]string, error) {
  277. var rows []struct {
  278. Name string `gorm:"column:name"`
  279. }
  280. if err := tx.Raw(`PRAGMA table_info("` + table + `")`).Scan(&rows).Error; err != nil {
  281. return nil, err
  282. }
  283. cols := make([]string, 0, len(rows))
  284. for _, r := range rows {
  285. cols = append(cols, r.Name)
  286. }
  287. return cols, nil
  288. }
  289. func rebuildInboundsWithoutInlineUniquePort() error {
  290. return db.Transaction(func(tx *gorm.DB) error {
  291. var list []sqliteIndexListRow
  292. if err := tx.Raw(`PRAGMA index_list('inbounds')`).Scan(&list).Error; err != nil {
  293. return err
  294. }
  295. for _, idx := range list {
  296. if idx.Origin != "c" {
  297. continue
  298. }
  299. if err := tx.Exec(`DROP INDEX IF EXISTS "` + idx.Name + `"`).Error; err != nil {
  300. return err
  301. }
  302. }
  303. if err := tx.Exec(`ALTER TABLE inbounds RENAME TO inbounds_legacy_rebuild`).Error; err != nil {
  304. return err
  305. }
  306. if err := tx.Migrator().CreateTable(&model.Inbound{}); err != nil {
  307. return err
  308. }
  309. newCols, err := sqliteTableColumns(tx, "inbounds")
  310. if err != nil {
  311. return err
  312. }
  313. oldCols, err := sqliteTableColumns(tx, "inbounds_legacy_rebuild")
  314. if err != nil {
  315. return err
  316. }
  317. oldSet := make(map[string]struct{}, len(oldCols))
  318. for _, c := range oldCols {
  319. oldSet[c] = struct{}{}
  320. }
  321. shared := make([]string, 0, len(newCols))
  322. for _, c := range newCols {
  323. if _, ok := oldSet[c]; ok {
  324. shared = append(shared, `"`+c+`"`)
  325. }
  326. }
  327. colList := strings.Join(shared, ", ")
  328. if err := tx.Exec(`INSERT INTO inbounds (` + colList + `) SELECT ` + colList + ` FROM inbounds_legacy_rebuild`).Error; err != nil {
  329. return err
  330. }
  331. return tx.Exec(`DROP TABLE inbounds_legacy_rebuild`).Error
  332. })
  333. }
  334. // AutoMigrate adds the columns; an older SQLite ALTER TABLE leaves them NULL,
  335. // and a NULL traffic_reset fails every ClientRecord scan, not just the new query.
  336. func migrateClientTrafficResetColumns() error {
  337. if db.Migrator().HasColumn(&model.ClientRecord{}, "traffic_reset") {
  338. if err := db.Exec("UPDATE clients SET traffic_reset = 'never' WHERE traffic_reset IS NULL").Error; err != nil {
  339. return err
  340. }
  341. }
  342. if db.Migrator().HasColumn(&model.ClientRecord{}, "traffic_reset_day") {
  343. if err := db.Exec("UPDATE clients SET traffic_reset_day = 1 WHERE traffic_reset_day IS NULL").Error; err != nil {
  344. return err
  345. }
  346. }
  347. return nil
  348. }
  349. // Existing clients keep weekly renewal disabled, including nullable columns
  350. // left by an earlier ALTER TABLE; configured nonzero weekdays are preserved.
  351. func migrateClientResetWeekdayColumns() error {
  352. for _, table := range []string{"clients", "client_traffics"} {
  353. if err := db.Table(table).Where("reset_weekday IS NULL").UpdateColumn("reset_weekday", 0).Error; err != nil {
  354. return err
  355. }
  356. }
  357. return nil
  358. }
  359. // AutoMigrate adds the column; this only backfills the NULLs an older SQLite
  360. // ALTER TABLE leaves behind, so the reaper's predicate never compares to NULL.
  361. func migrateSyncOrphanColumns() error {
  362. if !db.Migrator().HasColumn(&model.ClientRecord{}, "sync_orphaned_at") {
  363. return nil
  364. }
  365. return db.Exec("UPDATE clients SET sync_orphaned_at = 0 WHERE sync_orphaned_at IS NULL").Error
  366. }
  367. // The client identity checks match emails case-insensitively; without an
  368. // expression index (which no GORM struct tag can declare) they seq-scan.
  369. func migrateClientEmailLowerIndex() error {
  370. if db.Migrator().HasIndex(&model.ClientRecord{}, "idx_clients_email_lower") {
  371. return nil
  372. }
  373. return db.Exec("CREATE INDEX IF NOT EXISTS idx_clients_email_lower ON clients (LOWER(email))").Error
  374. }
  375. func migrateHostVerifyPeerCertByNameColumn() error {
  376. if !db.Migrator().HasColumn(&model.Host{}, "verify_peer_cert_by_name") {
  377. return nil
  378. }
  379. if IsPostgres() {
  380. var dataType string
  381. if err := db.Raw(
  382. `SELECT data_type FROM information_schema.columns WHERE table_name = 'hosts' AND column_name = 'verify_peer_cert_by_name'`,
  383. ).Scan(&dataType).Error; err != nil {
  384. return err
  385. }
  386. if dataType != "boolean" {
  387. return nil
  388. }
  389. if err := db.Exec(`ALTER TABLE hosts ALTER COLUMN verify_peer_cert_by_name DROP DEFAULT`).Error; err != nil {
  390. return err
  391. }
  392. return db.Exec(`ALTER TABLE hosts ALTER COLUMN verify_peer_cert_by_name TYPE text USING ''`).Error
  393. }
  394. 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
  395. }
  396. func seedHostsFromExternalProxy() error {
  397. var history []string
  398. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  399. return err
  400. }
  401. if slices.Contains(history, "HostsFromExternalProxy") {
  402. return nil
  403. }
  404. var inbounds []model.Inbound
  405. if err := db.Find(&inbounds).Error; err != nil {
  406. return err
  407. }
  408. return db.Transaction(func(tx *gorm.DB) error {
  409. for _, inbound := range inbounds {
  410. if _, err := CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  411. return err
  412. }
  413. }
  414. return tx.Create(&model.HistoryOfSeeders{SeederName: "HostsFromExternalProxy"}).Error
  415. })
  416. }
  417. func seedMtprotoCustomShareAddrToHosts() error {
  418. const seederName = "MtprotoCustomShareAddrToHosts"
  419. var count int64
  420. if err := db.Model(&model.HistoryOfSeeders{}).Where("seeder_name = ?", seederName).Count(&count).Error; err != nil {
  421. return err
  422. }
  423. if count > 0 {
  424. return nil
  425. }
  426. return db.Transaction(func(tx *gorm.DB) error {
  427. var inbounds []model.Inbound
  428. if err := tx.Where("protocol = ? AND TRIM(COALESCE(share_addr_strategy, '')) = ?", string(model.MTProto), "custom").Find(&inbounds).Error; err != nil {
  429. return err
  430. }
  431. for _, inbound := range inbounds {
  432. if err := CreateHostFromMtprotoCustomShareAddr(tx, inbound.Id, inbound.ShareAddr); err != nil {
  433. return err
  434. }
  435. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).Updates(map[string]any{
  436. "share_addr_strategy": "listen",
  437. "share_addr": "",
  438. }).Error; err != nil {
  439. return err
  440. }
  441. }
  442. return tx.Create(&model.HistoryOfSeeders{SeederName: seederName}).Error
  443. })
  444. }
  445. func CreateHostFromMtprotoCustomShareAddr(tx *gorm.DB, inboundId int, rawAddress string) error {
  446. address := strings.TrimPrefix(strings.TrimSuffix(strings.TrimSpace(rawAddress), "]"), "[")
  447. if address == "" {
  448. return nil
  449. }
  450. var sameAddress []model.Host
  451. if err := tx.Where("inbound_id = ? AND address = ? AND is_disabled = ?", inboundId, address, false).
  452. Find(&sameAddress).Error; err != nil {
  453. return err
  454. }
  455. for _, host := range sameAddress {
  456. if !slices.Contains(host.ExcludeFromSubTypes, "raw") {
  457. return nil
  458. }
  459. }
  460. return tx.Create(&model.Host{
  461. GroupId: random.NumLower(16), InboundId: inboundId,
  462. Remark: address, Address: address, Security: "same",
  463. }).Error
  464. }
  465. func seedWireguardPeersToClients() error {
  466. var history []string
  467. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  468. return err
  469. }
  470. if slices.Contains(history, "WireguardPeersToClients") {
  471. return nil
  472. }
  473. var inbounds []model.Inbound
  474. if err := db.Where("protocol = ?", string(model.WireGuard)).Find(&inbounds).Error; err != nil {
  475. return err
  476. }
  477. return db.Transaction(func(tx *gorm.DB) error {
  478. usedEmails := map[string]struct{}{}
  479. var existingEmails []string
  480. if err := tx.Model(&model.ClientRecord{}).Pluck("email", &existingEmails).Error; err != nil {
  481. return err
  482. }
  483. for _, e := range existingEmails {
  484. usedEmails[e] = struct{}{}
  485. }
  486. for _, inbound := range inbounds {
  487. if strings.TrimSpace(inbound.Settings) == "" {
  488. continue
  489. }
  490. var settings map[string]any
  491. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  492. log.Printf("WireguardPeersToClients: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  493. continue
  494. }
  495. peers, ok := settings["peers"].([]any)
  496. if !ok || len(peers) == 0 {
  497. continue
  498. }
  499. var linkCount int64
  500. if err := tx.Model(&model.ClientInbound{}).Where("inbound_id = ?", inbound.Id).Count(&linkCount).Error; err != nil {
  501. return err
  502. }
  503. if linkCount > 0 {
  504. continue
  505. }
  506. clientObjs := make([]any, 0, len(peers))
  507. for i, raw := range peers {
  508. obj, ok := raw.(map[string]any)
  509. if !ok {
  510. continue
  511. }
  512. email := wireguardPeerEmail(inbound.Remark, obj, i, usedEmails)
  513. usedEmails[email] = struct{}{}
  514. obj["email"] = email
  515. if sub, _ := obj["subId"].(string); strings.TrimSpace(sub) == "" {
  516. obj["subId"] = random.NumLower(16)
  517. }
  518. if _, ok := obj["enable"]; !ok {
  519. obj["enable"] = true
  520. }
  521. blob, err := json.Marshal(obj)
  522. if err != nil {
  523. continue
  524. }
  525. var c model.Client
  526. if err := json.Unmarshal(blob, &c); err != nil {
  527. log.Printf("WireguardPeersToClients: skip peer in inbound %d: %v", inbound.Id, err)
  528. continue
  529. }
  530. c.Email = email
  531. incoming := c.ToRecord()
  532. var row model.ClientRecord
  533. err = tx.Where("email = ?", email).First(&row).Error
  534. if errors.Is(err, gorm.ErrRecordNotFound) {
  535. if err := tx.Create(incoming).Error; err != nil {
  536. return err
  537. }
  538. row = *incoming
  539. } else if err != nil {
  540. return err
  541. } else {
  542. model.MergeClientRecord(&row, incoming)
  543. if err := tx.Save(&row).Error; err != nil {
  544. return err
  545. }
  546. }
  547. link := model.ClientInbound{ClientId: row.Id, InboundId: inbound.Id}
  548. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  549. FirstOrCreate(&link).Error; err != nil {
  550. return err
  551. }
  552. clientObjs = append(clientObjs, obj)
  553. }
  554. delete(settings, "peers")
  555. settings["clients"] = clientObjs
  556. newSettings, err := json.Marshal(settings)
  557. if err != nil {
  558. return err
  559. }
  560. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  561. Update("settings", string(newSettings)).Error; err != nil {
  562. return err
  563. }
  564. }
  565. return tx.Create(&model.HistoryOfSeeders{SeederName: "WireguardPeersToClients"}).Error
  566. })
  567. }
  568. func wireguardPeerEmail(remark string, peer map[string]any, index int, used map[string]struct{}) string {
  569. base := strings.TrimSpace(remark)
  570. if base == "" {
  571. base = "wg"
  572. }
  573. suffix := strconv.Itoa(index + 1)
  574. if c, ok := peer["comment"].(string); ok && strings.TrimSpace(c) != "" {
  575. suffix = strings.TrimSpace(c)
  576. }
  577. email := strings.ReplaceAll(base+"-"+suffix, " ", "-")
  578. candidate := email
  579. for n := 2; ; n++ {
  580. if _, taken := used[candidate]; !taken {
  581. return candidate
  582. }
  583. candidate = email + "-" + strconv.Itoa(n)
  584. }
  585. }
  586. // seedMtprotoSecretsToClients converts each legacy single-secret mtproto inbound
  587. // into a one-client inbound so MTProto joins the shared multi-client model: the
  588. // inbound-level secret becomes the first client's FakeTLS secret, and a
  589. // ClientRecord + client_inbounds link are created so per-client traffic, limits,
  590. // and share links work exactly like every other protocol. One-time, self-gated
  591. // on the "MtprotoSecretsToClients" seeder row. Mirrors seedWireguardPeersToClients.
  592. func seedMtprotoSecretsToClients() error {
  593. var history []string
  594. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  595. return err
  596. }
  597. if slices.Contains(history, "MtprotoSecretsToClients") {
  598. return nil
  599. }
  600. var inbounds []model.Inbound
  601. if err := db.Where("protocol = ?", string(model.MTProto)).Find(&inbounds).Error; err != nil {
  602. return err
  603. }
  604. return db.Transaction(func(tx *gorm.DB) error {
  605. usedEmails := map[string]struct{}{}
  606. var existingEmails []string
  607. if err := tx.Model(&model.ClientRecord{}).Pluck("email", &existingEmails).Error; err != nil {
  608. return err
  609. }
  610. for _, e := range existingEmails {
  611. usedEmails[e] = struct{}{}
  612. }
  613. for _, inbound := range inbounds {
  614. if strings.TrimSpace(inbound.Settings) == "" {
  615. continue
  616. }
  617. var settings map[string]any
  618. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  619. log.Printf("MtprotoSecretsToClients: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  620. continue
  621. }
  622. if clients, ok := settings["clients"].([]any); ok && len(clients) > 0 {
  623. continue
  624. }
  625. var linkCount int64
  626. if err := tx.Model(&model.ClientInbound{}).Where("inbound_id = ?", inbound.Id).Count(&linkCount).Error; err != nil {
  627. return err
  628. }
  629. if linkCount > 0 {
  630. continue
  631. }
  632. secret, _ := settings["secret"].(string)
  633. secret = strings.TrimSpace(secret)
  634. if secret == "" {
  635. domain, _ := settings["fakeTlsDomain"].(string)
  636. secret = model.GenerateFakeTLSSecret(strings.TrimSpace(domain))
  637. }
  638. email := mtprotoInboundClientEmail(inbound.Remark, usedEmails)
  639. usedEmails[email] = struct{}{}
  640. obj := map[string]any{
  641. "email": email,
  642. "secret": secret,
  643. "enable": true,
  644. "subId": random.NumLower(16),
  645. }
  646. c := model.Client{Email: email, Secret: secret, Enable: true, SubID: obj["subId"].(string)}
  647. incoming := c.ToRecord()
  648. var row model.ClientRecord
  649. err := tx.Where("email = ?", email).First(&row).Error
  650. if errors.Is(err, gorm.ErrRecordNotFound) {
  651. if err := tx.Create(incoming).Error; err != nil {
  652. return err
  653. }
  654. row = *incoming
  655. } else if err != nil {
  656. return err
  657. } else {
  658. model.MergeClientRecord(&row, incoming)
  659. if err := tx.Save(&row).Error; err != nil {
  660. return err
  661. }
  662. }
  663. link := model.ClientInbound{ClientId: row.Id, InboundId: inbound.Id}
  664. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  665. FirstOrCreate(&link).Error; err != nil {
  666. return err
  667. }
  668. delete(settings, "secret")
  669. settings["clients"] = []any{obj}
  670. newSettings, err := json.Marshal(settings)
  671. if err != nil {
  672. return err
  673. }
  674. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  675. Update("settings", string(newSettings)).Error; err != nil {
  676. return err
  677. }
  678. }
  679. return tx.Create(&model.HistoryOfSeeders{SeederName: "MtprotoSecretsToClients"}).Error
  680. })
  681. }
  682. // stripMtprotoInboundSecrets removes the vestigial inbound-level `secret` from
  683. // every mtproto inbound. seedMtprotoSecretsToClients already drops it while
  684. // converting legacy single-secret inbounds, but inbounds that already had clients
  685. // kept the dead field, and the old HealMtprotoSecret regenerated it on every
  686. // save. mtg and every share link read only per-client secrets, so the
  687. // inbound-level value is dead data that once leaked into stale, unusable links.
  688. // One-time, self-gated on the "StripMtprotoInboundSecrets" seeder row.
  689. func stripMtprotoInboundSecrets() error {
  690. var history []string
  691. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  692. return err
  693. }
  694. if slices.Contains(history, "StripMtprotoInboundSecrets") {
  695. return nil
  696. }
  697. var inbounds []model.Inbound
  698. if err := db.Where("protocol = ?", string(model.MTProto)).Find(&inbounds).Error; err != nil {
  699. return err
  700. }
  701. return db.Transaction(func(tx *gorm.DB) error {
  702. for _, inbound := range inbounds {
  703. stripped, ok := model.StripMtprotoInboundSecret(inbound.Settings)
  704. if !ok {
  705. continue
  706. }
  707. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  708. Update("settings", stripped).Error; err != nil {
  709. return err
  710. }
  711. }
  712. return tx.Create(&model.HistoryOfSeeders{SeederName: "StripMtprotoInboundSecrets"}).Error
  713. })
  714. }
  715. // mtprotoInboundClientEmail derives a stable, unique client email for a migrated
  716. // mtproto inbound from its remark.
  717. func mtprotoInboundClientEmail(remark string, used map[string]struct{}) string {
  718. base := strings.TrimSpace(remark)
  719. if base == "" {
  720. base = "mtproto"
  721. }
  722. email := strings.ReplaceAll(base, " ", "-")
  723. candidate := email
  724. for n := 2; ; n++ {
  725. if _, taken := used[candidate]; !taken {
  726. return candidate
  727. }
  728. candidate = email + "-" + strconv.Itoa(n)
  729. }
  730. }
  731. // CreateHostsFromExternalProxy parses a legacy streamSettings.externalProxy array
  732. // and inserts one Host row per entry on tx, returning the number of rows created.
  733. // It is the shared core of both the one-time seedHostsFromExternalProxy startup
  734. // migration and the inbound-import path: an inbound exported from a build that
  735. // predated the hosts table carries its external proxies inline in
  736. // streamSettings.externalProxy, and the startup migration is gated off after its
  737. // first run, so a freshly imported inbound must be converted here instead. Blank
  738. // or malformed streamSettings, or one without externalProxy entries, is a no-op.
  739. func CreateHostsFromExternalProxy(tx *gorm.DB, inboundId int, streamSettings string) (int, error) {
  740. if strings.TrimSpace(streamSettings) == "" {
  741. return 0, nil
  742. }
  743. var stream map[string]any
  744. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  745. return 0, nil
  746. }
  747. eps, ok := stream["externalProxy"].([]any)
  748. if !ok || len(eps) == 0 {
  749. return 0, nil
  750. }
  751. created := 0
  752. for i, raw := range eps {
  753. ep, ok := raw.(map[string]any)
  754. if !ok {
  755. continue
  756. }
  757. if err := tx.Create(externalProxyEntryToHost(inboundId, i, ep)).Error; err != nil {
  758. return created, err
  759. }
  760. created++
  761. }
  762. return created, nil
  763. }
  764. func externalProxyEntryToHost(inboundId, index int, ep map[string]any) *model.Host {
  765. security, _ := ep["forceTls"].(string)
  766. switch security {
  767. case "same", "tls", "none":
  768. default:
  769. security = "same"
  770. }
  771. dest, _ := ep["dest"].(string)
  772. port := 0
  773. if p, ok := ep["port"].(float64); ok {
  774. port = int(p)
  775. }
  776. remark, _ := ep["remark"].(string)
  777. if strings.TrimSpace(remark) == "" {
  778. remark = "imported " + strconv.Itoa(index+1)
  779. }
  780. if len(remark) > 256 {
  781. remark = remark[:256]
  782. }
  783. sni, _ := ep["sni"].(string)
  784. fingerprint, _ := ep["fingerprint"].(string)
  785. ech, _ := ep["echConfigList"].(string)
  786. return &model.Host{
  787. GroupId: random.NumLower(16),
  788. InboundId: inboundId,
  789. SortOrder: index,
  790. Remark: remark,
  791. Address: dest,
  792. Port: port,
  793. Security: security,
  794. Sni: sni,
  795. Fingerprint: fingerprint,
  796. Alpn: anyToNonEmptyStrings(ep["alpn"]),
  797. PinnedPeerCertSha256: anyToNonEmptyStrings(ep["pinnedPeerCertSha256"]),
  798. EchConfigList: ech,
  799. }
  800. }
  801. func anyToNonEmptyStrings(v any) []string {
  802. switch t := v.(type) {
  803. case []any:
  804. out := make([]string, 0, len(t))
  805. for _, e := range t {
  806. if s, ok := e.(string); ok && s != "" {
  807. out = append(out, s)
  808. }
  809. }
  810. return out
  811. case []string:
  812. out := make([]string, 0, len(t))
  813. for _, s := range t {
  814. if s != "" {
  815. out = append(out, s)
  816. }
  817. }
  818. return out
  819. default:
  820. return nil
  821. }
  822. }
  823. func pruneOrphanedHosts() error {
  824. res := db.Exec("DELETE FROM hosts WHERE inbound_id NOT IN (SELECT id FROM inbounds)")
  825. if res.Error != nil {
  826. log.Printf("Error pruning orphaned hosts rows: %v", res.Error)
  827. return res.Error
  828. }
  829. if res.RowsAffected > 0 {
  830. log.Printf("Pruned %d orphaned hosts row(s)", res.RowsAffected)
  831. }
  832. return nil
  833. }
  834. func pruneOrphanedClientInbounds() error {
  835. res := db.Exec("DELETE FROM client_inbounds WHERE inbound_id NOT IN (SELECT id FROM inbounds)")
  836. if res.Error != nil {
  837. log.Printf("Error pruning orphaned client_inbounds rows: %v", res.Error)
  838. return res.Error
  839. }
  840. if res.RowsAffected > 0 {
  841. log.Printf("Pruned %d orphaned client_inbounds row(s)", res.RowsAffected)
  842. }
  843. return nil
  844. }
  845. // migrateLegacySocksInboundsToMixed renames legacy socks inbounds to mixed.
  846. // The protocol enum dropped socks in favor of mixed (identical settings shape,
  847. // same behavior plus HTTP on the shared port), so rows predating the rename
  848. // fail model validation — most visibly when pushed to a node, where one legacy
  849. // inbound stalled the entire node's config and traffic sync (#5685).
  850. func migrateLegacySocksInboundsToMixed() error {
  851. res := db.Exec("UPDATE inbounds SET protocol = 'mixed' WHERE protocol = 'socks'")
  852. if res.Error != nil {
  853. log.Printf("Error migrating legacy socks inbounds to mixed: %v", res.Error)
  854. return res.Error
  855. }
  856. if res.RowsAffected > 0 {
  857. log.Printf("Migrated %d legacy socks inbound(s) to mixed", res.RowsAffected)
  858. }
  859. return nil
  860. }
  861. // migrateShadowsocksRemovedCiphers rewrites shadowsocks inbounds still using
  862. // the "none"/"plain" ciphers that xray-core v26.7.11 removed; one such row
  863. // makes the whole generated config unbuildable and keeps xray from starting.
  864. func migrateShadowsocksRemovedCiphers() error {
  865. var inbounds []model.Inbound
  866. if err := db.Where("protocol = ?", model.Shadowsocks).Find(&inbounds).Error; err != nil {
  867. return err
  868. }
  869. migrated := int64(0)
  870. for _, inbound := range inbounds {
  871. if strings.TrimSpace(inbound.Settings) == "" {
  872. continue
  873. }
  874. var settings map[string]any
  875. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  876. continue
  877. }
  878. changed := false
  879. if method, _ := settings["method"].(string); method != "" {
  880. if replacement, removed := model.ReplaceRemovedShadowsocksCipher(method); removed {
  881. settings["method"] = replacement
  882. changed = true
  883. }
  884. }
  885. if clients, ok := settings["clients"].([]any); ok {
  886. for i := range clients {
  887. cm, ok := clients[i].(map[string]any)
  888. if !ok {
  889. continue
  890. }
  891. method, _ := cm["method"].(string)
  892. if replacement, removed := model.ReplaceRemovedShadowsocksCipher(method); removed {
  893. cm["method"] = replacement
  894. clients[i] = cm
  895. changed = true
  896. }
  897. }
  898. }
  899. if !changed {
  900. continue
  901. }
  902. newSettings, err := json.MarshalIndent(settings, "", " ")
  903. if err != nil {
  904. log.Printf("migrateShadowsocksRemovedCiphers: skip inbound %d (marshal failed): %v", inbound.Id, err)
  905. continue
  906. }
  907. if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  908. Update("settings", string(newSettings)).Error; err != nil {
  909. return err
  910. }
  911. migrated++
  912. }
  913. if migrated > 0 {
  914. log.Printf("Rewrote removed shadowsocks cipher on %d inbound(s)", migrated)
  915. }
  916. return nil
  917. }
  918. // migrateVmessRemovedSecurities rewrites the vmess "none"/"zero" security
  919. // values that xray-core v26.7.11 removed to "auto" (what the core now treats
  920. // them as), on both the clients column and each vmess inbound's settings.
  921. func migrateVmessRemovedSecurities() error {
  922. res := db.Exec("UPDATE clients SET security = 'auto' WHERE security IN ('none', 'zero')")
  923. if res.Error != nil {
  924. log.Printf("Error migrating removed vmess security values on clients: %v", res.Error)
  925. return res.Error
  926. }
  927. if res.RowsAffected > 0 {
  928. log.Printf("Migrated %d client(s) off removed vmess security values", res.RowsAffected)
  929. }
  930. var inbounds []model.Inbound
  931. if err := db.Where("protocol = ?", model.VMESS).Find(&inbounds).Error; err != nil {
  932. return err
  933. }
  934. migrated := int64(0)
  935. for _, inbound := range inbounds {
  936. if strings.TrimSpace(inbound.Settings) == "" {
  937. continue
  938. }
  939. var settings map[string]any
  940. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  941. continue
  942. }
  943. clients, ok := settings["clients"].([]any)
  944. if !ok {
  945. continue
  946. }
  947. changed := false
  948. for i := range clients {
  949. cm, ok := clients[i].(map[string]any)
  950. if !ok {
  951. continue
  952. }
  953. if security, _ := cm["security"].(string); security == "none" || security == "zero" {
  954. cm["security"] = "auto"
  955. clients[i] = cm
  956. changed = true
  957. }
  958. }
  959. if !changed {
  960. continue
  961. }
  962. newSettings, err := json.MarshalIndent(settings, "", " ")
  963. if err != nil {
  964. log.Printf("migrateVmessRemovedSecurities: skip inbound %d (marshal failed): %v", inbound.Id, err)
  965. continue
  966. }
  967. if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  968. Update("settings", string(newSettings)).Error; err != nil {
  969. return err
  970. }
  971. migrated++
  972. }
  973. if migrated > 0 {
  974. log.Printf("Rewrote removed vmess security values on %d inbound(s)", migrated)
  975. }
  976. return nil
  977. }
  978. // migrateTgIDIndex creates an index on the clients.tg_id column so that
  979. // lookups by Telegram ID do not require a full table scan. The index tag
  980. // on the struct field already causes AutoMigrate to create it on new
  981. // installations; the explicit migration ensures existing databases get it.
  982. func migrateTgIDIndex() error {
  983. if db.Migrator().HasIndex(&model.ClientRecord{}, "idx_clients_tg_id") {
  984. return nil
  985. }
  986. return db.Migrator().CreateIndex(&model.ClientRecord{}, "TgID")
  987. }
  988. // normalizeInboundSubSortIndex lifts legacy zero defaults to 1.
  989. // Explicit negatives are left alone so primary inbounds can sort first.
  990. func normalizeInboundSubSortIndex() error {
  991. res := db.Exec("UPDATE inbounds SET sub_sort_index = 1 WHERE sub_sort_index = 0")
  992. if res.Error != nil {
  993. log.Printf("Error normalizing inbound sub_sort_index: %v", res.Error)
  994. return res.Error
  995. }
  996. if res.RowsAffected > 0 {
  997. log.Printf("Normalized sub_sort_index on %d inbound(s)", res.RowsAffected)
  998. }
  999. return nil
  1000. }
  1001. // normalizeClientExternalLinkEnable keeps external-link rows written before the
  1002. // enable column existed enabled; disabled rows from newer builds stay false.
  1003. func normalizeClientExternalLinkEnable() error {
  1004. res := db.Exec("UPDATE client_external_links SET enable = ? WHERE enable IS NULL", true)
  1005. if res.Error != nil {
  1006. log.Printf("Error normalizing client external link enable: %v", res.Error)
  1007. return res.Error
  1008. }
  1009. if res.RowsAffected > 0 {
  1010. log.Printf("Normalized enable on %d client external link(s)", res.RowsAffected)
  1011. }
  1012. return nil
  1013. }
  1014. // normalizeClientExternalLinkTimestamps zeroes the NULLs an older build could
  1015. // leave behind, so the sub-side expiry predicate never drops a legacy row.
  1016. func normalizeClientExternalLinkTimestamps() error {
  1017. res := db.Exec("UPDATE client_external_links SET expiry_time = 0 WHERE expiry_time IS NULL")
  1018. if res.Error != nil {
  1019. log.Printf("Error normalizing client external link expiry_time: %v", res.Error)
  1020. return res.Error
  1021. }
  1022. expiryRows := res.RowsAffected
  1023. res = db.Exec("UPDATE client_external_links SET last_fetch_at = 0 WHERE last_fetch_at IS NULL")
  1024. if res.Error != nil {
  1025. log.Printf("Error normalizing client external link last_fetch_at: %v", res.Error)
  1026. return res.Error
  1027. }
  1028. if expiryRows+res.RowsAffected > 0 {
  1029. log.Printf("Normalized timestamps on %d client external link(s)", expiryRows+res.RowsAffected)
  1030. }
  1031. return nil
  1032. }
  1033. // repairOverflowedTrafficCounters heals traffic counters that historic
  1034. // compounding bugs pushed past int64: on SQLite an overflowing INTEGER is
  1035. // silently promoted to REAL, after which the column no longer scans into the
  1036. // Go int64 field and every reader of the table fails (#5762). REAL cells are
  1037. // cast back to INTEGER (SQLite caps the cast at math.MaxInt64), then values
  1038. // are clamped into [0, TrafficMax] on both backends so the next delta cannot
  1039. // overflow again.
  1040. func repairOverflowedTrafficCounters() error {
  1041. targets := []struct {
  1042. table string
  1043. columns []string
  1044. }{
  1045. {"client_traffics", []string{"up", "down"}},
  1046. {"inbounds", []string{"up", "down"}},
  1047. {"outbound_traffics", []string{"up", "down", "total"}},
  1048. {"node_client_traffics", []string{"up", "down"}},
  1049. }
  1050. for _, target := range targets {
  1051. for _, col := range target.columns {
  1052. statements := []string{
  1053. fmt.Sprintf("UPDATE %s SET %s = %d WHERE %s > %d", target.table, col, TrafficMax, col, TrafficMax),
  1054. fmt.Sprintf("UPDATE %s SET %s = 0 WHERE %s < 0", target.table, col, col),
  1055. }
  1056. if !IsPostgres() {
  1057. statements = append([]string{
  1058. fmt.Sprintf("UPDATE %s SET %s = CAST(%s AS INTEGER) WHERE typeof(%s) = 'real'", target.table, col, col, col),
  1059. }, statements...)
  1060. }
  1061. var repaired int64
  1062. for _, statement := range statements {
  1063. res := db.Exec(statement)
  1064. if res.Error != nil {
  1065. log.Printf("Error repairing %s.%s: %v", target.table, col, res.Error)
  1066. return res.Error
  1067. }
  1068. repaired += res.RowsAffected
  1069. }
  1070. if repaired > 0 {
  1071. log.Printf("Repaired %d overflowed %s.%s value(s)", repaired, target.table, col)
  1072. }
  1073. }
  1074. }
  1075. return nil
  1076. }
  1077. // dedupeInboundSettingsClients collapses duplicate same-email entries inside
  1078. // every inbound's settings.clients array, keeping the first occurrence.
  1079. // Retried or raced multi-node client adds on older builds appended the same
  1080. // client several times (#5770), which the client lists then rendered as
  1081. // phantom duplicates. Runs on every start (idempotent, writes only changed
  1082. // rows) because a restored backup or a not-yet-upgraded node's snapshot can
  1083. // reintroduce duplicates.
  1084. func dedupeInboundSettingsClients() error {
  1085. var inbounds []model.Inbound
  1086. if err := db.Find(&inbounds).Error; err != nil {
  1087. return err
  1088. }
  1089. repaired := int64(0)
  1090. for _, inbound := range inbounds {
  1091. if strings.TrimSpace(inbound.Settings) == "" {
  1092. continue
  1093. }
  1094. var settings map[string]any
  1095. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1096. continue
  1097. }
  1098. clients, _ := settings["clients"].([]any)
  1099. if len(clients) < 2 {
  1100. continue
  1101. }
  1102. seen := make(map[string]struct{}, len(clients))
  1103. kept := make([]any, 0, len(clients))
  1104. for _, c := range clients {
  1105. if cm, ok := c.(map[string]any); ok {
  1106. if email, _ := cm["email"].(string); email != "" {
  1107. key := strings.ToLower(email)
  1108. if _, dup := seen[key]; dup {
  1109. continue
  1110. }
  1111. seen[key] = struct{}{}
  1112. }
  1113. }
  1114. kept = append(kept, c)
  1115. }
  1116. if len(kept) == len(clients) {
  1117. continue
  1118. }
  1119. settings["clients"] = kept
  1120. newSettings, err := json.MarshalIndent(settings, "", " ")
  1121. if err != nil {
  1122. log.Printf("dedupeInboundSettingsClients: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1123. continue
  1124. }
  1125. if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1126. Update("settings", string(newSettings)).Error; err != nil {
  1127. return err
  1128. }
  1129. repaired++
  1130. }
  1131. if repaired > 0 {
  1132. log.Printf("Removed duplicate client entries from %d inbound(s)", repaired)
  1133. }
  1134. return nil
  1135. }
  1136. func isIgnorableDuplicateColumnErr(gdb *gorm.DB, err error, mdl any) bool {
  1137. if err == nil {
  1138. return false
  1139. }
  1140. errMsg := strings.ToLower(err.Error())
  1141. const sqlitePrefix = "duplicate column name:"
  1142. if _, after, ok := strings.Cut(errMsg, sqlitePrefix); ok {
  1143. col := strings.TrimSpace(after)
  1144. col = strings.Trim(col, "`\"[]")
  1145. return col != "" && gdb != nil && gdb.Migrator().HasColumn(mdl, col)
  1146. }
  1147. if strings.Contains(errMsg, "already exists") && strings.Contains(errMsg, "column ") {
  1148. if _, after, ok := strings.Cut(errMsg, "column \""); ok {
  1149. rest := after
  1150. if e := strings.Index(rest, "\""); e > 0 {
  1151. col := rest[:e]
  1152. return col != "" && gdb != nil && gdb.Migrator().HasColumn(mdl, col)
  1153. }
  1154. }
  1155. }
  1156. return false
  1157. }
  1158. func initUser() error {
  1159. empty, err := isTableEmpty("users")
  1160. if err != nil {
  1161. log.Printf("Error checking if users table is empty: %v", err)
  1162. return err
  1163. }
  1164. if empty {
  1165. hashedPassword, err := crypto.HashPasswordAsBcrypt(defaultPassword)
  1166. if err != nil {
  1167. log.Printf("Error hashing default password: %v", err)
  1168. return err
  1169. }
  1170. user := &model.User{
  1171. Username: defaultUsername,
  1172. Password: hashedPassword,
  1173. }
  1174. return db.Create(user).Error
  1175. }
  1176. return nil
  1177. }
  1178. func seedRandomSubscriptionPaths() error {
  1179. settings := []model.Setting{
  1180. {Key: "subPath", Value: "/" + random.NumLower(16) + "/"},
  1181. {Key: "subJsonPath", Value: "/" + random.NumLower(16) + "/"},
  1182. {Key: "subClashPath", Value: "/" + random.NumLower(16) + "/"},
  1183. }
  1184. return db.Transaction(func(tx *gorm.DB) error {
  1185. for i := range settings {
  1186. if err := tx.Where("key = ?", settings[i].Key).FirstOrCreate(&settings[i]).Error; err != nil {
  1187. return err
  1188. }
  1189. }
  1190. return nil
  1191. })
  1192. }
  1193. func runSeeders(isUsersEmpty bool) error {
  1194. empty, err := isTableEmpty("history_of_seeders")
  1195. if err != nil {
  1196. log.Printf("Error checking if users table is empty: %v", err)
  1197. return err
  1198. }
  1199. if empty && isUsersEmpty {
  1200. seeders := []string{"UserPasswordHash", "ClientsTable", "InboundClientsArrayFix", "InboundClientTgIdFix2", "InboundClientSubIdFix", "FreedomFinalRulesReverseFix", "FreedomFinalRulesPrivateEgressBlock", "UppercaseFreedomFinalRulesFix", "InboundRealityFinalmaskTcpStrip", "ApiTokensHash", "LegacyProxySettingsCleanup", "OutboundRemovedKeysFix", "FreedomDomainStrategyFix", "DNSOutboundLegacyKeysFix", "DNSOutboundQTypeZeroFix", "WireguardPeersToClients", "MtprotoSecretsToClients", "NodeInboundsAdopted", "ResetIpLimitNoFail2ban"}
  1201. for _, name := range seeders {
  1202. if err := db.Create(&model.HistoryOfSeeders{SeederName: name}).Error; err != nil {
  1203. return err
  1204. }
  1205. }
  1206. return seedApiTokens()
  1207. }
  1208. var seedersHistory []string
  1209. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &seedersHistory).Error; err != nil {
  1210. log.Printf("Error fetching seeder history: %v", err)
  1211. return err
  1212. }
  1213. if !slices.Contains(seedersHistory, "UserPasswordHash") && !isUsersEmpty {
  1214. var users []model.User
  1215. if err := db.Find(&users).Error; err != nil {
  1216. log.Printf("Error fetching users for password migration: %v", err)
  1217. return err
  1218. }
  1219. for _, user := range users {
  1220. if crypto.IsHashed(user.Password) {
  1221. continue
  1222. }
  1223. hashedPassword, err := crypto.HashPasswordAsBcrypt(user.Password)
  1224. if err != nil {
  1225. log.Printf("Error hashing password for user '%s': %v", user.Username, err)
  1226. return err
  1227. }
  1228. if err := db.Model(&user).Update("password", hashedPassword).Error; err != nil {
  1229. log.Printf("Error updating password for user '%s': %v", user.Username, err)
  1230. return err
  1231. }
  1232. }
  1233. hashSeeder := &model.HistoryOfSeeders{
  1234. SeederName: "UserPasswordHash",
  1235. }
  1236. if err := db.Create(hashSeeder).Error; err != nil {
  1237. return err
  1238. }
  1239. }
  1240. if !slices.Contains(seedersHistory, "ApiTokensTable") {
  1241. if err := seedApiTokens(); err != nil {
  1242. return err
  1243. }
  1244. }
  1245. if !slices.Contains(seedersHistory, "ApiTokensHash") {
  1246. if err := hashExistingApiTokens(); err != nil {
  1247. return err
  1248. }
  1249. }
  1250. if !slices.Contains(seedersHistory, "ClientsTable") {
  1251. if err := seedClientsFromInboundJSON(); err != nil {
  1252. return err
  1253. }
  1254. }
  1255. if !slices.Contains(seedersHistory, "InboundClientsArrayFix") {
  1256. if err := normalizeInboundClientsArray(); err != nil {
  1257. return err
  1258. }
  1259. }
  1260. if !slices.Contains(seedersHistory, "InboundClientTgIdFix2") {
  1261. if err := normalizeInboundClientTgId(); err != nil {
  1262. return err
  1263. }
  1264. }
  1265. if !slices.Contains(seedersHistory, "InboundClientSubIdFix") {
  1266. if err := normalizeInboundClientSubId(); err != nil {
  1267. return err
  1268. }
  1269. }
  1270. if !slices.Contains(seedersHistory, "FreedomFinalRulesReverseFix") {
  1271. if err := normalizeFreedomFinalRules(); err != nil {
  1272. return err
  1273. }
  1274. }
  1275. if !slices.Contains(seedersHistory, "FreedomFinalRulesPrivateEgressBlock") {
  1276. if err := hardenFreedomFinalRules(); err != nil {
  1277. return err
  1278. }
  1279. }
  1280. if !slices.Contains(seedersHistory, "UppercaseFreedomFinalRulesFix") {
  1281. if err := fixUppercaseFreedomFinalRules(); err != nil {
  1282. return err
  1283. }
  1284. }
  1285. if !slices.Contains(seedersHistory, "InboundRealityFinalmaskTcpStrip") {
  1286. if err := stripRealityFinalmaskTcp(); err != nil {
  1287. return err
  1288. }
  1289. }
  1290. if !slices.Contains(seedersHistory, "LegacyProxySettingsCleanup") {
  1291. if err := clearLegacyProxySettings(); err != nil {
  1292. return err
  1293. }
  1294. }
  1295. if !slices.Contains(seedersHistory, "OutboundRemovedKeysFix") {
  1296. if err := migrateOutboundRemovedKeys(); err != nil {
  1297. return err
  1298. }
  1299. }
  1300. if !slices.Contains(seedersHistory, "FreedomDomainStrategyFix") {
  1301. if err := migrateFreedomDomainStrategy(); err != nil {
  1302. return err
  1303. }
  1304. }
  1305. if !slices.Contains(seedersHistory, "DNSOutboundLegacyKeysFix") {
  1306. if err := migrateDNSOutboundLegacyKeys(); err != nil {
  1307. return err
  1308. }
  1309. }
  1310. if !slices.Contains(seedersHistory, "DNSOutboundQTypeZeroFix") {
  1311. if err := migrateDNSOutboundQTypeZero(); err != nil {
  1312. return err
  1313. }
  1314. }
  1315. if !slices.Contains(seedersHistory, "NodeInboundsAdopted") {
  1316. if err := seedNodeInboundsAdopted(); err != nil {
  1317. return err
  1318. }
  1319. }
  1320. if err := seedHostsFromExternalProxy(); err != nil {
  1321. return err
  1322. }
  1323. if err := seedMtprotoCustomShareAddrToHosts(); err != nil {
  1324. return err
  1325. }
  1326. if err := resetIpLimitsWithoutFail2ban(); err != nil {
  1327. return err
  1328. }
  1329. if err := seedWireguardPeersToClients(); err != nil {
  1330. return err
  1331. }
  1332. if err := backfillEmptyHostGroupIds(); err != nil {
  1333. return err
  1334. }
  1335. // Self-gated on the "MtprotoSecretsToClients" row.
  1336. if err := seedMtprotoSecretsToClients(); err != nil {
  1337. return err
  1338. }
  1339. // Self-gated on the "StripMtprotoInboundSecrets" row. Must run after the
  1340. // seeder above so legacy single-secret inbounds are first converted to a
  1341. // client (which preserves the secret) before the inbound-level copy is
  1342. // dropped from every mtproto inbound.
  1343. if err := stripMtprotoInboundSecrets(); err != nil {
  1344. return err
  1345. }
  1346. // Idempotent, not seeder-gated: bad values can re-enter via a restored
  1347. // backup, so re-check on every start.
  1348. return normalizeSettingPaths()
  1349. }
  1350. // seedNodeInboundsAdopted keeps the pre-existing reconcile behavior for nodes
  1351. // that were already syncing before the inbounds_adopted_at gate was introduced.
  1352. func seedNodeInboundsAdopted() error {
  1353. if err := db.Model(&model.Node{}).
  1354. Where("inbounds_adopted_at = 0").
  1355. Update("inbounds_adopted_at", time.Now().Unix()).Error; err != nil {
  1356. return err
  1357. }
  1358. return db.Create(&model.HistoryOfSeeders{SeederName: "NodeInboundsAdopted"}).Error
  1359. }
  1360. // backfillEmptyHostGroupIds is idempotent and not seeder-gated: builds that
  1361. // predate group ids on the inbound-import path (and restored backups) can
  1362. // re-introduce hosts rows with an empty group_id, and such rows render as a
  1363. // synthetic fallback_<id> group the update/delete API cannot address, so
  1364. // re-check on every start.
  1365. func backfillEmptyHostGroupIds() error {
  1366. var hosts []*model.Host
  1367. if err := db.Where("group_id = '' OR group_id IS NULL").Find(&hosts).Error; err != nil {
  1368. return err
  1369. }
  1370. if len(hosts) == 0 {
  1371. return nil
  1372. }
  1373. return db.Transaction(func(tx *gorm.DB) error {
  1374. for _, h := range hosts {
  1375. if err := tx.Model(h).Update("group_id", random.NumLower(16)).Error; err != nil {
  1376. return err
  1377. }
  1378. }
  1379. return nil
  1380. })
  1381. }
  1382. func resetIpLimitsWithoutFail2ban() error {
  1383. var history []string
  1384. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  1385. return err
  1386. }
  1387. if slices.Contains(history, "ResetIpLimitNoFail2ban") {
  1388. return nil
  1389. }
  1390. state, probeErr := fail2banEnforcementState()
  1391. if state == fail2banEnforcing {
  1392. return db.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
  1393. }
  1394. if state == fail2banUnknown {
  1395. log.Printf("ResetIpLimitNoFail2ban: fail2ban-client present but not runnable (%v); keeping configured IP limits, will retry next start", probeErr)
  1396. return nil
  1397. }
  1398. var inbounds []model.Inbound
  1399. if err := db.Find(&inbounds).Error; err != nil {
  1400. return err
  1401. }
  1402. return db.Transaction(func(tx *gorm.DB) error {
  1403. for _, inbound := range inbounds {
  1404. if strings.TrimSpace(inbound.Settings) == "" {
  1405. continue
  1406. }
  1407. var settings map[string]any
  1408. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1409. log.Printf("ResetIpLimitNoFail2ban: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1410. continue
  1411. }
  1412. clients, ok := settings["clients"].([]any)
  1413. if !ok {
  1414. continue
  1415. }
  1416. mutated := false
  1417. for i, raw := range clients {
  1418. obj, ok := raw.(map[string]any)
  1419. if !ok {
  1420. continue
  1421. }
  1422. v, present := obj["limitIp"]
  1423. if !present {
  1424. continue
  1425. }
  1426. if n, isNum := v.(float64); isNum && n == 0 {
  1427. continue
  1428. }
  1429. obj["limitIp"] = 0
  1430. clients[i] = obj
  1431. mutated = true
  1432. }
  1433. if !mutated {
  1434. continue
  1435. }
  1436. settings["clients"] = clients
  1437. newSettings, err := json.MarshalIndent(settings, "", " ")
  1438. if err != nil {
  1439. log.Printf("ResetIpLimitNoFail2ban: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1440. continue
  1441. }
  1442. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1443. Update("settings", string(newSettings)).Error; err != nil {
  1444. return err
  1445. }
  1446. }
  1447. if err := tx.Model(&model.ClientRecord{}).Where("limit_ip <> ?", 0).
  1448. Update("limit_ip", 0).Error; err != nil {
  1449. return err
  1450. }
  1451. return tx.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
  1452. })
  1453. }
  1454. type fail2banState int
  1455. const (
  1456. fail2banEnforcing fail2banState = iota
  1457. fail2banAbsent
  1458. fail2banUnknown
  1459. )
  1460. // fail2banEnforcementState separates "fail2ban is not installed" from "the probe
  1461. // itself failed", so a transient failure never drives an irreversible cleanup.
  1462. func fail2banEnforcementState() (fail2banState, error) {
  1463. if v, ok := os.LookupEnv("XUI_ENABLE_FAIL2BAN"); ok && v != "true" {
  1464. return fail2banAbsent, nil
  1465. }
  1466. if runtime.GOOS == "windows" {
  1467. return fail2banAbsent, nil
  1468. }
  1469. if _, err := exec.LookPath("fail2ban-client"); err != nil {
  1470. return fail2banAbsent, nil
  1471. }
  1472. if err := exec.CommandContext(context.Background(), "fail2ban-client", "-h").Run(); err != nil {
  1473. return fail2banUnknown, err
  1474. }
  1475. return fail2banEnforcing, nil
  1476. }
  1477. func clearLegacyProxySettings() error {
  1478. return db.Transaction(func(tx *gorm.DB) error {
  1479. if err := tx.Where("key IN ?", []string{"panelProxy", "tgBotProxy"}).
  1480. Delete(&model.Setting{}).Error; err != nil {
  1481. return err
  1482. }
  1483. return tx.Create(&model.HistoryOfSeeders{SeederName: "LegacyProxySettingsCleanup"}).Error
  1484. })
  1485. }
  1486. func migrateOutboundRemovedKeys() error {
  1487. var setting model.Setting
  1488. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  1489. if errors.Is(err, gorm.ErrRecordNotFound) {
  1490. return db.Create(&model.HistoryOfSeeders{SeederName: "OutboundRemovedKeysFix"}).Error
  1491. }
  1492. if err != nil {
  1493. return err
  1494. }
  1495. updated, changed, rErr := rewriteRemovedOutboundKeys(setting.Value)
  1496. if rErr != nil {
  1497. log.Printf("OutboundRemovedKeysFix: skip (invalid xrayTemplateConfig json): %v", rErr)
  1498. return db.Create(&model.HistoryOfSeeders{SeederName: "OutboundRemovedKeysFix"}).Error
  1499. }
  1500. return db.Transaction(func(tx *gorm.DB) error {
  1501. if changed {
  1502. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  1503. Update("value", updated).Error; err != nil {
  1504. return err
  1505. }
  1506. }
  1507. return tx.Create(&model.HistoryOfSeeders{SeederName: "OutboundRemovedKeysFix"}).Error
  1508. })
  1509. }
  1510. // rewriteRemovedOutboundKeys moves outbound proxySettings.tag to sockopt.dialerProxy
  1511. // and drops freedom sockopt.addressPortStrategy: xray-core v26.9.8 refuses both.
  1512. func rewriteRemovedOutboundKeys(raw string) (string, bool, error) {
  1513. if strings.TrimSpace(raw) == "" {
  1514. return raw, false, nil
  1515. }
  1516. var cfg map[string]any
  1517. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  1518. return raw, false, err
  1519. }
  1520. outbounds, ok := cfg["outbounds"].([]any)
  1521. if !ok {
  1522. return raw, false, nil
  1523. }
  1524. changed := false
  1525. for _, ob := range outbounds {
  1526. obj, ok := ob.(map[string]any)
  1527. if !ok {
  1528. continue
  1529. }
  1530. if proxySettings, present := obj["proxySettings"]; present {
  1531. ps, _ := proxySettings.(map[string]any)
  1532. if tag, _ := ps["tag"].(string); tag != "" {
  1533. sockopt := outboundSockopt(obj, true)
  1534. if current, _ := sockopt["dialerProxy"].(string); current == "" {
  1535. sockopt["dialerProxy"] = tag
  1536. }
  1537. }
  1538. delete(obj, "proxySettings")
  1539. changed = true
  1540. }
  1541. if proto, _ := obj["protocol"].(string); strings.EqualFold(proto, "freedom") {
  1542. if sockopt := outboundSockopt(obj, false); sockopt != nil {
  1543. if _, present := sockopt["addressPortStrategy"]; present {
  1544. delete(sockopt, "addressPortStrategy")
  1545. changed = true
  1546. }
  1547. }
  1548. }
  1549. }
  1550. if !changed {
  1551. return raw, false, nil
  1552. }
  1553. out, err := json.MarshalIndent(cfg, "", " ")
  1554. if err != nil {
  1555. return raw, false, err
  1556. }
  1557. return string(out), true, nil
  1558. }
  1559. func outboundSockopt(obj map[string]any, create bool) map[string]any {
  1560. stream, _ := obj["streamSettings"].(map[string]any)
  1561. if stream == nil {
  1562. if !create {
  1563. return nil
  1564. }
  1565. stream = map[string]any{}
  1566. obj["streamSettings"] = stream
  1567. }
  1568. sockopt, _ := stream["sockopt"].(map[string]any)
  1569. if sockopt == nil {
  1570. if !create {
  1571. return nil
  1572. }
  1573. sockopt = map[string]any{}
  1574. stream["sockopt"] = sockopt
  1575. }
  1576. return sockopt
  1577. }
  1578. func migrateFreedomDomainStrategy() error {
  1579. var setting model.Setting
  1580. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  1581. if errors.Is(err, gorm.ErrRecordNotFound) {
  1582. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomDomainStrategyFix"}).Error
  1583. }
  1584. if err != nil {
  1585. return err
  1586. }
  1587. updated, changed, rErr := rewriteFreedomDomainStrategy(setting.Value)
  1588. if rErr != nil {
  1589. log.Printf("FreedomDomainStrategyFix: skip (invalid xrayTemplateConfig json): %v", rErr)
  1590. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomDomainStrategyFix"}).Error
  1591. }
  1592. return db.Transaction(func(tx *gorm.DB) error {
  1593. if changed {
  1594. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  1595. Update("value", updated).Error; err != nil {
  1596. return err
  1597. }
  1598. }
  1599. return tx.Create(&model.HistoryOfSeeders{SeederName: "FreedomDomainStrategyFix"}).Error
  1600. })
  1601. }
  1602. // rewriteFreedomDomainStrategy moves a freedom outbound's legacy strategy keys
  1603. // into sockopt.domainStrategy, the placement the core's deprecation warning names.
  1604. func rewriteFreedomDomainStrategy(raw string) (string, bool, error) {
  1605. if strings.TrimSpace(raw) == "" {
  1606. return raw, false, nil
  1607. }
  1608. var cfg map[string]any
  1609. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  1610. return raw, false, err
  1611. }
  1612. outbounds, ok := cfg["outbounds"].([]any)
  1613. if !ok {
  1614. return raw, false, nil
  1615. }
  1616. changed := false
  1617. for _, ob := range outbounds {
  1618. obj, ok := ob.(map[string]any)
  1619. if !ok {
  1620. continue
  1621. }
  1622. if proto, _ := obj["protocol"].(string); !strings.EqualFold(proto, "freedom") {
  1623. continue
  1624. }
  1625. settings, hasSettings := obj["settings"].(map[string]any)
  1626. _, hasRoot := obj["targetStrategy"]
  1627. _, hasSettingsTarget := settings["targetStrategy"]
  1628. _, hasSettingsDomain := settings["domainStrategy"]
  1629. if !hasRoot && !hasSettingsTarget && !hasSettingsDomain {
  1630. continue
  1631. }
  1632. strategy := freedomMigratedStrategy(obj, settings)
  1633. delete(obj, "targetStrategy")
  1634. if hasSettings {
  1635. delete(settings, "targetStrategy")
  1636. delete(settings, "domainStrategy")
  1637. }
  1638. if strategy != "" {
  1639. outboundSockopt(obj, true)["domainStrategy"] = strategy
  1640. }
  1641. changed = true
  1642. }
  1643. if !changed {
  1644. return raw, false, nil
  1645. }
  1646. out, err := json.MarshalIndent(cfg, "", " ")
  1647. if err != nil {
  1648. return raw, false, err
  1649. }
  1650. return string(out), true, nil
  1651. }
  1652. // freedomMigratedStrategy clones the core's own resolution order for a freedom
  1653. // outbound (infra/conf/freedom.go), returning "" when none of them holds one.
  1654. func freedomMigratedStrategy(obj, settings map[string]any) string {
  1655. if s, ok := freedomStrategyValue(obj["targetStrategy"]); ok && !strings.EqualFold(s, "asis") {
  1656. return s
  1657. }
  1658. legacy := settings["targetStrategy"]
  1659. if s, ok := legacy.(string); !ok || s == "" {
  1660. legacy = settings["domainStrategy"]
  1661. }
  1662. if s, ok := freedomStrategyValue(legacy); ok && !strings.EqualFold(s, "asis") {
  1663. return s
  1664. }
  1665. return ""
  1666. }
  1667. // freedomStrategyValue reports a strategy the core accepts -- anything else is a
  1668. // hard load error in freedom and sockopt alike, so it cannot be migrated.
  1669. func freedomStrategyValue(value any) (string, bool) {
  1670. s, ok := value.(string)
  1671. if !ok || s == "" {
  1672. return "", false
  1673. }
  1674. if !freedomDomainStrategies[strings.ToLower(s)] {
  1675. return "", false
  1676. }
  1677. return s, true
  1678. }
  1679. var freedomDomainStrategies = map[string]bool{
  1680. "asis": true, "useip": true, "useipv4": true, "useipv6": true,
  1681. "useipv4v6": true, "useipv6v4": true, "forceip": true, "forceipv4": true,
  1682. "forceipv6": true, "forceipv4v6": true, "forceipv6v4": true,
  1683. }
  1684. // migrateDNSOutboundLegacyKeys rewrites stored dns outbounds once, because the
  1685. // core logs nonIPQuery/blockTypes as deprecated on every config load.
  1686. func migrateDNSOutboundLegacyKeys() error {
  1687. var setting model.Setting
  1688. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  1689. if errors.Is(err, gorm.ErrRecordNotFound) {
  1690. return db.Create(&model.HistoryOfSeeders{SeederName: "DNSOutboundLegacyKeysFix"}).Error
  1691. }
  1692. if err != nil {
  1693. return err
  1694. }
  1695. updated, changed, rErr := rewriteDNSOutboundLegacyKeys(setting.Value)
  1696. if rErr != nil {
  1697. log.Printf("DNSOutboundLegacyKeysFix: skip (invalid xrayTemplateConfig json): %v", rErr)
  1698. return db.Create(&model.HistoryOfSeeders{SeederName: "DNSOutboundLegacyKeysFix"}).Error
  1699. }
  1700. return db.Transaction(func(tx *gorm.DB) error {
  1701. if changed {
  1702. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  1703. Update("value", updated).Error; err != nil {
  1704. return err
  1705. }
  1706. }
  1707. return tx.Create(&model.HistoryOfSeeders{SeederName: "DNSOutboundLegacyKeysFix"}).Error
  1708. })
  1709. }
  1710. // rewriteDNSOutboundLegacyKeys turns a dns outbound's legacy nonIPQuery and
  1711. // blockTypes into rules, in the order the core's legacy builder used.
  1712. func rewriteDNSOutboundLegacyKeys(raw string) (string, bool, error) {
  1713. if strings.TrimSpace(raw) == "" {
  1714. return raw, false, nil
  1715. }
  1716. var cfg map[string]any
  1717. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  1718. return raw, false, err
  1719. }
  1720. outbounds, ok := cfg["outbounds"].([]any)
  1721. if !ok {
  1722. return raw, false, nil
  1723. }
  1724. changed := false
  1725. for _, ob := range outbounds {
  1726. obj, ok := ob.(map[string]any)
  1727. if !ok {
  1728. continue
  1729. }
  1730. if proto, _ := obj["protocol"].(string); !strings.EqualFold(proto, "dns") {
  1731. continue
  1732. }
  1733. settings, _ := obj["settings"].(map[string]any)
  1734. if settings == nil {
  1735. continue
  1736. }
  1737. nonIPQuery, hasMode := settings["nonIPQuery"]
  1738. blockTypes, hasTypes := settings["blockTypes"]
  1739. // JSON null is absent to the core, which decides on nil pointers.
  1740. hasMode = hasMode && nonIPQuery != nil
  1741. hasTypes = hasTypes && blockTypes != nil
  1742. if !hasMode && !hasTypes {
  1743. continue
  1744. }
  1745. // The core refuses legacy keys next to real rules, so existing rules win.
  1746. if rules, hasRules := settings["rules"]; !hasRules || rules == nil {
  1747. settings["rules"] = legacyDNSOutboundRules(dnsNonIPQueryMode(nonIPQuery), legacyDNSBlockTypes(blockTypes))
  1748. }
  1749. delete(settings, "nonIPQuery")
  1750. delete(settings, "blockTypes")
  1751. changed = true
  1752. }
  1753. if !changed {
  1754. return raw, false, nil
  1755. }
  1756. out, err := json.MarshalIndent(cfg, "", " ")
  1757. if err != nil {
  1758. return raw, false, err
  1759. }
  1760. return string(out), true, nil
  1761. }
  1762. // dnsNonIPQueryMode reports the mode the core resolved: everything but drop and
  1763. // skip meant reject, and any other value never loaded in the first place.
  1764. func dnsNonIPQueryMode(value any) string {
  1765. mode, _ := value.(string)
  1766. mode = strings.ToLower(strings.TrimSpace(mode))
  1767. if mode == "drop" || mode == "skip" {
  1768. return mode
  1769. }
  1770. return "reject"
  1771. }
  1772. // legacyDNSBlockTypes accepts every shape the old card could save: a list, a
  1773. // bare number, or a comma-separated string, minus the qTypes the core rejects.
  1774. func legacyDNSBlockTypes(value any) []int {
  1775. items, ok := value.([]any)
  1776. if !ok && value != nil {
  1777. items = []any{value}
  1778. }
  1779. var out []int
  1780. for _, item := range items {
  1781. for _, part := range strings.Split(fmt.Sprint(item), ",") {
  1782. qType, err := strconv.Atoi(strings.TrimSpace(part))
  1783. if err != nil || qType < 0 || qType > 65535 {
  1784. continue
  1785. }
  1786. out = append(out, qType)
  1787. }
  1788. }
  1789. return out
  1790. }
  1791. // legacyDNSOutboundRules mirrors the core's own legacy dns policy: the blocked
  1792. // qTypes, then the hijack, then the mode's answer for everything else.
  1793. func legacyDNSOutboundRules(mode string, blockTypes []int) []any {
  1794. rules := make([]any, 0, 3)
  1795. if len(blockTypes) > 0 {
  1796. rule := map[string]any{"action": "drop", "qType": dnsQTypeValue(blockTypes)}
  1797. if mode == "reject" {
  1798. rule["action"] = "return"
  1799. rule["rCode"] = 5
  1800. }
  1801. rules = append(rules, rule)
  1802. }
  1803. rules = append(rules, map[string]any{"action": "hijack", "qType": "1,28"})
  1804. fallback := map[string]any{"action": "direct"}
  1805. switch mode {
  1806. case "reject":
  1807. fallback["action"] = "return"
  1808. fallback["rCode"] = 5
  1809. case "drop":
  1810. fallback["action"] = "drop"
  1811. }
  1812. return append(rules, fallback)
  1813. }
  1814. // dnsQTypeValue keeps a lone qType a number the way the core marshals one, except
  1815. // 0: the core drops a numeric 0, and a rule with no qTypes matches every query.
  1816. func dnsQTypeValue(blockTypes []int) any {
  1817. if len(blockTypes) == 1 && blockTypes[0] != 0 {
  1818. return blockTypes[0]
  1819. }
  1820. parts := make([]string, 0, len(blockTypes))
  1821. for _, qType := range blockTypes {
  1822. parts = append(parts, strconv.Itoa(qType))
  1823. }
  1824. return strings.Join(parts, ",")
  1825. }
  1826. // migrateDNSOutboundQTypeZero repairs the numeric qType 0 that 3.8.0's legacy-keys
  1827. // seeder stored, which that seeder's own history row keeps it from revisiting.
  1828. func migrateDNSOutboundQTypeZero() error {
  1829. var setting model.Setting
  1830. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  1831. if errors.Is(err, gorm.ErrRecordNotFound) {
  1832. return db.Create(&model.HistoryOfSeeders{SeederName: "DNSOutboundQTypeZeroFix"}).Error
  1833. }
  1834. if err != nil {
  1835. return err
  1836. }
  1837. updated, changed, rErr := RewriteDNSOutboundQTypeZero(setting.Value)
  1838. if rErr != nil {
  1839. log.Printf("DNSOutboundQTypeZeroFix: skip (invalid xrayTemplateConfig json): %v", rErr)
  1840. return db.Create(&model.HistoryOfSeeders{SeederName: "DNSOutboundQTypeZeroFix"}).Error
  1841. }
  1842. return db.Transaction(func(tx *gorm.DB) error {
  1843. if changed {
  1844. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  1845. Update("value", updated).Error; err != nil {
  1846. return err
  1847. }
  1848. }
  1849. return tx.Create(&model.HistoryOfSeeders{SeederName: "DNSOutboundQTypeZeroFix"}).Error
  1850. })
  1851. }
  1852. // RewriteDNSOutboundQTypeZero spells a dns rule's numeric qType 0 as "0", the one
  1853. // form the core reads as query type 0 rather than as every query.
  1854. func RewriteDNSOutboundQTypeZero(raw string) (string, bool, error) {
  1855. if strings.TrimSpace(raw) == "" {
  1856. return raw, false, nil
  1857. }
  1858. var cfg map[string]any
  1859. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  1860. return raw, false, err
  1861. }
  1862. outbounds, _ := cfg["outbounds"].([]any)
  1863. changed := false
  1864. for _, ob := range outbounds {
  1865. obj, _ := ob.(map[string]any)
  1866. if proto, _ := obj["protocol"].(string); !strings.EqualFold(proto, "dns") {
  1867. continue
  1868. }
  1869. settings, _ := obj["settings"].(map[string]any)
  1870. rules, _ := settings["rules"].([]any)
  1871. for _, r := range rules {
  1872. rule, _ := r.(map[string]any)
  1873. if qType, ok := rule["qType"].(float64); ok && qType == 0 {
  1874. rule["qType"] = "0"
  1875. changed = true
  1876. }
  1877. }
  1878. }
  1879. if !changed {
  1880. return raw, false, nil
  1881. }
  1882. out, err := json.MarshalIndent(cfg, "", " ")
  1883. if err != nil {
  1884. return raw, false, err
  1885. }
  1886. return string(out), true, nil
  1887. }
  1888. func normalizeSettingPaths() error {
  1889. pathKeys := []string{"webBasePath", "subPath", "subJsonPath", "subClashPath"}
  1890. var rows []model.Setting
  1891. if err := db.Where("key IN ?", pathKeys).Find(&rows).Error; err != nil {
  1892. return err
  1893. }
  1894. for _, row := range rows {
  1895. fixed := row.Value
  1896. if !strings.HasPrefix(fixed, "/") {
  1897. fixed = "/" + fixed
  1898. }
  1899. if !strings.HasSuffix(fixed, "/") {
  1900. fixed += "/"
  1901. }
  1902. if fixed == row.Value {
  1903. continue
  1904. }
  1905. if err := db.Model(&model.Setting{}).Where("id = ?", row.Id).
  1906. Update("value", fixed).Error; err != nil {
  1907. return err
  1908. }
  1909. }
  1910. return nil
  1911. }
  1912. func normalizeInboundClientTgId() error {
  1913. var inbounds []model.Inbound
  1914. if err := db.Find(&inbounds).Error; err != nil {
  1915. return err
  1916. }
  1917. return db.Transaction(func(tx *gorm.DB) error {
  1918. for _, inbound := range inbounds {
  1919. if strings.TrimSpace(inbound.Settings) == "" {
  1920. continue
  1921. }
  1922. var settings map[string]any
  1923. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1924. log.Printf("InboundClientTgIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1925. continue
  1926. }
  1927. clients, ok := settings["clients"].([]any)
  1928. if !ok {
  1929. continue
  1930. }
  1931. mutated := false
  1932. for i, raw := range clients {
  1933. obj, ok := raw.(map[string]any)
  1934. if !ok {
  1935. continue
  1936. }
  1937. tgRaw, present := obj["tgId"]
  1938. if !present {
  1939. continue
  1940. }
  1941. v, isFloat := tgRaw.(float64)
  1942. if isFloat && !math.IsNaN(v) && !math.IsInf(v, 0) && v == math.Trunc(v) {
  1943. continue
  1944. }
  1945. obj["tgId"] = int64(0)
  1946. if s, isStr := tgRaw.(string); isStr {
  1947. if id, err := strconv.ParseInt(strings.ReplaceAll(strings.TrimSpace(s), " ", ""), 10, 64); err == nil {
  1948. obj["tgId"] = id
  1949. }
  1950. }
  1951. clients[i] = obj
  1952. mutated = true
  1953. }
  1954. if !mutated {
  1955. continue
  1956. }
  1957. settings["clients"] = clients
  1958. newSettings, err := json.MarshalIndent(settings, "", " ")
  1959. if err != nil {
  1960. log.Printf("InboundClientTgIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1961. continue
  1962. }
  1963. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1964. Update("settings", string(newSettings)).Error; err != nil {
  1965. return err
  1966. }
  1967. }
  1968. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientTgIdFix2"}).Error
  1969. })
  1970. }
  1971. func normalizeInboundClientSubId() error {
  1972. var inbounds []model.Inbound
  1973. if err := db.Find(&inbounds).Error; err != nil {
  1974. return err
  1975. }
  1976. return db.Transaction(func(tx *gorm.DB) error {
  1977. for _, inbound := range inbounds {
  1978. if strings.TrimSpace(inbound.Settings) == "" {
  1979. continue
  1980. }
  1981. var settings map[string]any
  1982. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1983. log.Printf("InboundClientSubIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1984. continue
  1985. }
  1986. clients, ok := settings["clients"].([]any)
  1987. if !ok {
  1988. continue
  1989. }
  1990. mutated := false
  1991. for i, raw := range clients {
  1992. obj, ok := raw.(map[string]any)
  1993. if !ok {
  1994. continue
  1995. }
  1996. existing, _ := obj["subId"].(string)
  1997. if strings.TrimSpace(existing) != "" {
  1998. continue
  1999. }
  2000. obj["subId"] = random.NumLower(16)
  2001. clients[i] = obj
  2002. mutated = true
  2003. }
  2004. if !mutated {
  2005. continue
  2006. }
  2007. settings["clients"] = clients
  2008. newSettings, err := json.MarshalIndent(settings, "", " ")
  2009. if err != nil {
  2010. log.Printf("InboundClientSubIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  2011. continue
  2012. }
  2013. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  2014. Update("settings", string(newSettings)).Error; err != nil {
  2015. return err
  2016. }
  2017. }
  2018. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientSubIdFix"}).Error
  2019. })
  2020. }
  2021. func normalizeInboundClientsArray() error {
  2022. var inbounds []model.Inbound
  2023. if err := db.Find(&inbounds).Error; err != nil {
  2024. return err
  2025. }
  2026. return db.Transaction(func(tx *gorm.DB) error {
  2027. for _, inbound := range inbounds {
  2028. if strings.TrimSpace(inbound.Settings) == "" {
  2029. continue
  2030. }
  2031. var settings map[string]any
  2032. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2033. log.Printf("InboundClientsArrayFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  2034. continue
  2035. }
  2036. raw, exists := settings["clients"]
  2037. if !exists || raw != nil {
  2038. continue
  2039. }
  2040. settings["clients"] = []any{}
  2041. newSettings, err := json.MarshalIndent(settings, "", " ")
  2042. if err != nil {
  2043. log.Printf("InboundClientsArrayFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  2044. continue
  2045. }
  2046. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  2047. Update("settings", string(newSettings)).Error; err != nil {
  2048. return err
  2049. }
  2050. }
  2051. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientsArrayFix"}).Error
  2052. })
  2053. }
  2054. func normalizeFreedomFinalRules() error {
  2055. var setting model.Setting
  2056. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  2057. if errors.Is(err, gorm.ErrRecordNotFound) {
  2058. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  2059. }
  2060. if err != nil {
  2061. return err
  2062. }
  2063. updated, changed, rErr := rewriteFreedomFinalRules(setting.Value)
  2064. if rErr != nil {
  2065. log.Printf("FreedomFinalRulesReverseFix: skip (invalid xrayTemplateConfig json): %v", rErr)
  2066. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  2067. }
  2068. return db.Transaction(func(tx *gorm.DB) error {
  2069. if changed {
  2070. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  2071. Update("value", updated).Error; err != nil {
  2072. return err
  2073. }
  2074. }
  2075. return tx.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  2076. })
  2077. }
  2078. func rewriteFreedomFinalRules(raw string) (string, bool, error) {
  2079. if strings.TrimSpace(raw) == "" {
  2080. return raw, false, nil
  2081. }
  2082. var cfg map[string]any
  2083. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  2084. return raw, false, err
  2085. }
  2086. outbounds, ok := cfg["outbounds"].([]any)
  2087. if !ok {
  2088. return raw, false, nil
  2089. }
  2090. changed := false
  2091. for _, ob := range outbounds {
  2092. obj, ok := ob.(map[string]any)
  2093. if !ok {
  2094. continue
  2095. }
  2096. if proto, _ := obj["protocol"].(string); !strings.EqualFold(proto, "freedom") {
  2097. continue
  2098. }
  2099. settings, ok := obj["settings"].(map[string]any)
  2100. if !ok {
  2101. continue
  2102. }
  2103. if !isLegacyPrivateOnlyFinalRules(settings["finalRules"]) {
  2104. continue
  2105. }
  2106. settings["finalRules"] = []any{map[string]any{"action": "allow"}}
  2107. changed = true
  2108. }
  2109. if !changed {
  2110. return raw, false, nil
  2111. }
  2112. out, err := json.MarshalIndent(cfg, "", " ")
  2113. if err != nil {
  2114. return raw, false, err
  2115. }
  2116. return string(out), true, nil
  2117. }
  2118. func isLegacyPrivateOnlyFinalRules(v any) bool {
  2119. rules, ok := v.([]any)
  2120. if !ok || len(rules) != 1 {
  2121. return false
  2122. }
  2123. rule, ok := rules[0].(map[string]any)
  2124. if !ok {
  2125. return false
  2126. }
  2127. if action, _ := rule["action"].(string); action != "allow" {
  2128. return false
  2129. }
  2130. ips, ok := rule["ip"].([]any)
  2131. if !ok || len(ips) != 1 {
  2132. return false
  2133. }
  2134. if s, _ := ips[0].(string); s != "geoip:private" {
  2135. return false
  2136. }
  2137. for k := range rule {
  2138. if k != "action" && k != "ip" {
  2139. return false
  2140. }
  2141. }
  2142. return true
  2143. }
  2144. func isUnrestrictedFreedomFinalRules(v any, present bool) bool {
  2145. if !present || v == nil {
  2146. return true
  2147. }
  2148. rules, ok := v.([]any)
  2149. return ok && len(rules) == 0
  2150. }
  2151. func hardenFreedomFinalRules() error {
  2152. var setting model.Setting
  2153. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  2154. if errors.Is(err, gorm.ErrRecordNotFound) {
  2155. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesPrivateEgressBlock"}).Error
  2156. }
  2157. if err != nil {
  2158. return err
  2159. }
  2160. updated, changed, rErr := rewriteFreedomFinalRulesPrivateEgress(setting.Value)
  2161. if rErr != nil {
  2162. log.Printf("FreedomFinalRulesPrivateEgressBlock: skip (invalid xrayTemplateConfig json): %v", rErr)
  2163. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesPrivateEgressBlock"}).Error
  2164. }
  2165. return db.Transaction(func(tx *gorm.DB) error {
  2166. if changed {
  2167. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  2168. Update("value", updated).Error; err != nil {
  2169. return err
  2170. }
  2171. }
  2172. return tx.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesPrivateEgressBlock"}).Error
  2173. })
  2174. }
  2175. func rewriteFreedomFinalRulesPrivateEgress(raw string) (string, bool, error) {
  2176. if strings.TrimSpace(raw) == "" {
  2177. return raw, false, nil
  2178. }
  2179. var cfg map[string]any
  2180. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  2181. return raw, false, err
  2182. }
  2183. outbounds, ok := cfg["outbounds"].([]any)
  2184. if !ok {
  2185. return raw, false, nil
  2186. }
  2187. changed := false
  2188. for _, ob := range outbounds {
  2189. obj, ok := ob.(map[string]any)
  2190. if !ok {
  2191. continue
  2192. }
  2193. if proto, _ := obj["protocol"].(string); !strings.EqualFold(proto, "freedom") {
  2194. continue
  2195. }
  2196. settings, ok := obj["settings"].(map[string]any)
  2197. if !ok {
  2198. continue
  2199. }
  2200. finalRules, present := settings["finalRules"]
  2201. if !isUnrestrictedFreedomFinalRules(finalRules, present) &&
  2202. !isAllowOnlyFinalRules(finalRules) &&
  2203. !isLegacyPrivateOnlyFinalRules(finalRules) {
  2204. continue
  2205. }
  2206. settings["finalRules"] = []any{
  2207. map[string]any{"action": "block", "ip": []any{"geoip:private"}},
  2208. map[string]any{"action": "allow"},
  2209. }
  2210. changed = true
  2211. }
  2212. if !changed {
  2213. return raw, false, nil
  2214. }
  2215. out, err := json.MarshalIndent(cfg, "", " ")
  2216. if err != nil {
  2217. return raw, false, err
  2218. }
  2219. return string(out), true, nil
  2220. }
  2221. func fixUppercaseFreedomFinalRules() error {
  2222. var setting model.Setting
  2223. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  2224. if errors.Is(err, gorm.ErrRecordNotFound) {
  2225. return db.Create(&model.HistoryOfSeeders{SeederName: "UppercaseFreedomFinalRulesFix"}).Error
  2226. }
  2227. if err != nil {
  2228. return err
  2229. }
  2230. updated, changed, rErr := rewriteUppercaseFreedomFinalRules(setting.Value)
  2231. if rErr != nil {
  2232. log.Printf("UppercaseFreedomFinalRulesFix: skip (invalid xrayTemplateConfig json): %v", rErr)
  2233. return db.Create(&model.HistoryOfSeeders{SeederName: "UppercaseFreedomFinalRulesFix"}).Error
  2234. }
  2235. return db.Transaction(func(tx *gorm.DB) error {
  2236. if changed {
  2237. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  2238. Update("value", updated).Error; err != nil {
  2239. return err
  2240. }
  2241. }
  2242. return tx.Create(&model.HistoryOfSeeders{SeederName: "UppercaseFreedomFinalRulesFix"}).Error
  2243. })
  2244. }
  2245. // Re-runs both finalRules rewrites, because the rows of the two seeders above it
  2246. // already exist on any panel that walked past a differently spelled outbound.
  2247. func rewriteUppercaseFreedomFinalRules(raw string) (string, bool, error) {
  2248. if !hasNonLowercaseFreedomOutbound(raw) {
  2249. return raw, false, nil
  2250. }
  2251. reversed, reversedChanged, err := rewriteFreedomFinalRules(raw)
  2252. if err != nil {
  2253. return raw, false, err
  2254. }
  2255. hardened, hardenedChanged, err := rewriteFreedomFinalRulesPrivateEgress(reversed)
  2256. if err != nil {
  2257. return raw, false, err
  2258. }
  2259. if !reversedChanged && !hardenedChanged {
  2260. return raw, false, nil
  2261. }
  2262. return hardened, true, nil
  2263. }
  2264. func hasNonLowercaseFreedomOutbound(raw string) bool {
  2265. if strings.TrimSpace(raw) == "" {
  2266. return false
  2267. }
  2268. var cfg map[string]any
  2269. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  2270. return false
  2271. }
  2272. outbounds, ok := cfg["outbounds"].([]any)
  2273. if !ok {
  2274. return false
  2275. }
  2276. for _, ob := range outbounds {
  2277. obj, ok := ob.(map[string]any)
  2278. if !ok {
  2279. continue
  2280. }
  2281. if proto, _ := obj["protocol"].(string); strings.EqualFold(proto, "freedom") && proto != "freedom" {
  2282. return true
  2283. }
  2284. }
  2285. return false
  2286. }
  2287. func stripRealityFinalmaskTcp() error {
  2288. var inbounds []model.Inbound
  2289. if err := db.Find(&inbounds).Error; err != nil {
  2290. return err
  2291. }
  2292. return db.Transaction(func(tx *gorm.DB) error {
  2293. for i := range inbounds {
  2294. updated, changed := stripRealityFinalmaskTcpFromStream(inbounds[i].StreamSettings)
  2295. if !changed {
  2296. continue
  2297. }
  2298. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbounds[i].Id).
  2299. Update("stream_settings", updated).Error; err != nil {
  2300. return err
  2301. }
  2302. log.Printf("InboundRealityFinalmaskTcpStrip: removed finalmask.tcp from REALITY inbound %d (%s)", inbounds[i].Id, inbounds[i].Tag)
  2303. }
  2304. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundRealityFinalmaskTcpStrip"}).Error
  2305. })
  2306. }
  2307. func stripRealityFinalmaskTcpFromStream(raw string) (string, bool) {
  2308. if strings.TrimSpace(raw) == "" {
  2309. return raw, false
  2310. }
  2311. var stream map[string]any
  2312. if err := json.Unmarshal([]byte(raw), &stream); err != nil {
  2313. return raw, false
  2314. }
  2315. if sec, _ := stream["security"].(string); sec != "reality" {
  2316. return raw, false
  2317. }
  2318. finalmask, ok := stream["finalmask"].(map[string]any)
  2319. if !ok {
  2320. return raw, false
  2321. }
  2322. if tcp, _ := finalmask["tcp"].([]any); len(tcp) == 0 {
  2323. return raw, false
  2324. }
  2325. delete(finalmask, "tcp")
  2326. if len(finalmask) == 0 {
  2327. delete(stream, "finalmask")
  2328. }
  2329. out, err := json.Marshal(stream)
  2330. if err != nil {
  2331. return raw, false
  2332. }
  2333. return string(out), true
  2334. }
  2335. func isAllowOnlyFinalRules(v any) bool {
  2336. rules, ok := v.([]any)
  2337. if !ok || len(rules) != 1 {
  2338. return false
  2339. }
  2340. rule, ok := rules[0].(map[string]any)
  2341. if !ok {
  2342. return false
  2343. }
  2344. if action, _ := rule["action"].(string); action != "allow" {
  2345. return false
  2346. }
  2347. for k := range rule {
  2348. if k != "action" {
  2349. return false
  2350. }
  2351. }
  2352. return true
  2353. }
  2354. func normalizeClientJSONFields(obj map[string]any) {
  2355. normalizeInt := func(key string) {
  2356. raw, exists := obj[key]
  2357. if !exists {
  2358. return
  2359. }
  2360. s, ok := raw.(string)
  2361. if !ok {
  2362. return
  2363. }
  2364. trimmed := strings.ReplaceAll(strings.TrimSpace(s), " ", "")
  2365. if trimmed == "" {
  2366. delete(obj, key)
  2367. return
  2368. }
  2369. if n, err := strconv.ParseInt(trimmed, 10, 64); err == nil {
  2370. obj[key] = n
  2371. } else {
  2372. delete(obj, key)
  2373. }
  2374. }
  2375. for _, k := range []string{"tgId", "limitIp", "totalGB", "expiryTime", "reset", "created_at", "updated_at"} {
  2376. normalizeInt(k)
  2377. }
  2378. }
  2379. func seedClientsFromInboundJSON() error {
  2380. var inbounds []model.Inbound
  2381. if err := db.Find(&inbounds).Error; err != nil {
  2382. return err
  2383. }
  2384. return db.Transaction(func(tx *gorm.DB) error {
  2385. byEmail := map[string]*model.ClientRecord{}
  2386. var existing []model.ClientRecord
  2387. if err := tx.Find(&existing).Error; err != nil {
  2388. return err
  2389. }
  2390. for i := range existing {
  2391. byEmail[existing[i].Email] = &existing[i]
  2392. }
  2393. for _, inbound := range inbounds {
  2394. if strings.TrimSpace(inbound.Settings) == "" {
  2395. continue
  2396. }
  2397. var settings map[string]any
  2398. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2399. log.Printf("ClientsTable seed: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  2400. continue
  2401. }
  2402. rawList, ok := settings["clients"].([]any)
  2403. if !ok {
  2404. continue
  2405. }
  2406. for _, raw := range rawList {
  2407. obj, ok := raw.(map[string]any)
  2408. if !ok {
  2409. continue
  2410. }
  2411. normalizeClientJSONFields(obj)
  2412. blob, err := json.Marshal(obj)
  2413. if err != nil {
  2414. continue
  2415. }
  2416. var c model.Client
  2417. if err := json.Unmarshal(blob, &c); err != nil {
  2418. log.Printf("ClientsTable seed: skip client in inbound %d (unmarshal failed): %v; payload=%s",
  2419. inbound.Id, err, string(blob))
  2420. continue
  2421. }
  2422. email := strings.TrimSpace(c.Email)
  2423. if email == "" {
  2424. continue
  2425. }
  2426. incoming := c.ToRecord()
  2427. row, dup := byEmail[email]
  2428. if !dup {
  2429. if err := tx.Create(incoming).Error; err != nil {
  2430. return err
  2431. }
  2432. byEmail[email] = incoming
  2433. row = incoming
  2434. } else {
  2435. conflicts := model.MergeClientRecord(row, incoming)
  2436. for _, x := range conflicts {
  2437. log.Printf("client merge: email=%s conflict on %s old=%v new=%v kept=%v",
  2438. email, x.Field, x.Old, x.New, x.Kept)
  2439. }
  2440. if err := tx.Save(row).Error; err != nil {
  2441. return err
  2442. }
  2443. }
  2444. link := model.ClientInbound{
  2445. ClientId: row.Id,
  2446. InboundId: inbound.Id,
  2447. FlowOverride: c.Flow,
  2448. }
  2449. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  2450. FirstOrCreate(&link).Error; err != nil {
  2451. return err
  2452. }
  2453. }
  2454. }
  2455. return tx.Create(&model.HistoryOfSeeders{SeederName: "ClientsTable"}).Error
  2456. })
  2457. }
  2458. func seedApiTokens() error {
  2459. empty, err := isTableEmpty("api_tokens")
  2460. if err != nil {
  2461. return err
  2462. }
  2463. if empty {
  2464. var legacy model.Setting
  2465. err := db.Model(model.Setting{}).Where("key = ?", "apiToken").First(&legacy).Error
  2466. if err == nil && legacy.Value != "" {
  2467. row := &model.ApiToken{
  2468. Name: "default",
  2469. Token: legacy.Value,
  2470. Enabled: true,
  2471. }
  2472. if err := db.Create(row).Error; err != nil {
  2473. log.Printf("Error migrating legacy apiToken: %v", err)
  2474. return err
  2475. }
  2476. }
  2477. }
  2478. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensTable"}).Error
  2479. }
  2480. func hashExistingApiTokens() error {
  2481. var rows []*model.ApiToken
  2482. if err := db.Find(&rows).Error; err != nil {
  2483. return err
  2484. }
  2485. for _, r := range rows {
  2486. if crypto.IsSHA256Hex(r.Token) {
  2487. continue
  2488. }
  2489. hashed := crypto.HashTokenSHA256(r.Token)
  2490. if err := db.Model(model.ApiToken{}).Where("id = ?", r.Id).Update("token", hashed).Error; err != nil {
  2491. log.Printf("Error hashing api token %d: %v", r.Id, err)
  2492. return err
  2493. }
  2494. }
  2495. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensHash"}).Error
  2496. }
  2497. func isTableEmpty(tableName string) (bool, error) {
  2498. var count int64
  2499. err := db.Table(tableName).Count(&count).Error
  2500. return count == 0, err
  2501. }
  2502. func InitDB(dbPath string) error {
  2503. var gormLogger logger.Interface
  2504. if config.IsDebug() {
  2505. gormLogger = logger.New(
  2506. log.New(os.Stdout, "\r\n", log.LstdFlags),
  2507. logger.Config{
  2508. SlowThreshold: time.Second,
  2509. LogLevel: logger.Info,
  2510. IgnoreRecordNotFoundError: true,
  2511. Colorful: true,
  2512. },
  2513. )
  2514. } else {
  2515. gormLogger = logger.Discard
  2516. }
  2517. c := &gorm.Config{Logger: gormLogger, DisableForeignKeyConstraintWhenMigrating: true}
  2518. var err error
  2519. switch config.GetDBKind() {
  2520. case "postgres":
  2521. dsn := config.GetDBDSN()
  2522. if dsn == "" {
  2523. return errors.New("XUI_DB_TYPE=postgres but XUI_DB_DSN is empty")
  2524. }
  2525. db, err = openPostgresWithRetry(dsn, c)
  2526. if err != nil {
  2527. return err
  2528. }
  2529. default:
  2530. dir := path.Dir(dbPath)
  2531. if err = os.MkdirAll(dir, 0o700); err != nil {
  2532. return err
  2533. }
  2534. if err = cleanupSQLiteBackupDirs(filepath.Dir(dbPath)); err != nil {
  2535. log.Printf("clean SQLite backup directories: %v", err)
  2536. }
  2537. sync := sqliteSynchronous()
  2538. journal := sqliteJournalMode()
  2539. dsn := dbPath + "?_journal_mode=" + journal + "&_busy_timeout=10000&_synchronous=" + sync + "&_txlock=immediate"
  2540. db, err = gorm.Open(sqlite.Open(dsn), c)
  2541. if err != nil {
  2542. return err
  2543. }
  2544. if err := restrictSQLiteFilePerms(dbPath); err != nil {
  2545. log.Printf("restrict SQLite file permissions: %v", err)
  2546. }
  2547. sqlDB, err := db.DB()
  2548. if err != nil {
  2549. return err
  2550. }
  2551. pragmas := []string{
  2552. "PRAGMA journal_mode=" + journal,
  2553. "PRAGMA busy_timeout=10000",
  2554. "PRAGMA synchronous=" + sync,
  2555. fmt.Sprintf("PRAGMA cache_size=-%d", envInt("XUI_DB_CACHE_MB", 32)*1024),
  2556. fmt.Sprintf("PRAGMA mmap_size=%d", int64(envInt("XUI_DB_MMAP_MB", 256))*1024*1024),
  2557. "PRAGMA temp_store=MEMORY",
  2558. }
  2559. for _, p := range pragmas {
  2560. if _, err := sqlDB.ExecContext(context.Background(), p); err != nil {
  2561. return err
  2562. }
  2563. }
  2564. }
  2565. sqlDB, err := db.DB()
  2566. if err != nil {
  2567. return err
  2568. }
  2569. var maxOpen, maxIdle int
  2570. switch config.GetDBKind() {
  2571. case "postgres":
  2572. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 25)
  2573. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 25)
  2574. default:
  2575. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 8)
  2576. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 4)
  2577. }
  2578. sqlDB.SetMaxOpenConns(maxOpen)
  2579. sqlDB.SetMaxIdleConns(maxIdle)
  2580. sqlDB.SetConnMaxLifetime(time.Hour)
  2581. sqlDB.SetConnMaxIdleTime(30 * time.Minute)
  2582. if err := initModels(); err != nil {
  2583. return err
  2584. }
  2585. isUsersEmpty, err := isTableEmpty("users")
  2586. if err != nil {
  2587. return err
  2588. }
  2589. if isUsersEmpty {
  2590. if err := seedRandomSubscriptionPaths(); err != nil {
  2591. return err
  2592. }
  2593. }
  2594. if err := initUser(); err != nil {
  2595. return err
  2596. }
  2597. return runSeeders(isUsersEmpty)
  2598. }
  2599. func normalizeApiTokenCreatedAtSeconds() error {
  2600. return db.Model(&model.ApiToken{}).
  2601. Where("created_at >= ?", model.ApiTokenUnixMillisecondsThreshold).
  2602. UpdateColumn("created_at", gorm.Expr("created_at / ?", 1000)).Error
  2603. }
  2604. func migrateApiTokenScopeAndExpiry() error {
  2605. m := db.Migrator()
  2606. if !m.HasColumn(&model.ApiToken{}, "Scope") {
  2607. if err := m.AddColumn(&model.ApiToken{}, "Scope"); err != nil {
  2608. return err
  2609. }
  2610. }
  2611. if !m.HasColumn(&model.ApiToken{}, "ExpiresAt") {
  2612. if err := m.AddColumn(&model.ApiToken{}, "ExpiresAt"); err != nil {
  2613. return err
  2614. }
  2615. }
  2616. return db.Model(&model.ApiToken{}).Where("scope IS NULL OR TRIM(scope) = ''").
  2617. Updates(map[string]any{"scope": model.ApiScopeAdmin, "expires_at": 0}).Error
  2618. }
  2619. // openPostgresWithRetry retries the initial PostgreSQL connection with
  2620. // backoff so a database that starts slower than the panel (or drops out
  2621. // briefly) does not immediately kill the process and trip systemd's
  2622. // restart loop. Every failed attempt logs the real driver error, which
  2623. // used to be buried behind a generic startup failure.
  2624. func openPostgresWithRetry(dsn string, c *gorm.Config) (*gorm.DB, error) {
  2625. delays := []time.Duration{0, 2 * time.Second, 5 * time.Second, 10 * time.Second, 20 * time.Second, 30 * time.Second}
  2626. var lastErr error
  2627. for i, delay := range delays {
  2628. if delay > 0 {
  2629. time.Sleep(delay)
  2630. }
  2631. conn, err := gorm.Open(postgres.Open(dsn), c)
  2632. if err == nil {
  2633. if i > 0 {
  2634. log.Printf("postgres connection established on attempt %d/%d", i+1, len(delays))
  2635. }
  2636. return conn, nil
  2637. }
  2638. lastErr = err
  2639. log.Printf("postgres connection attempt %d/%d failed: %v", i+1, len(delays), err)
  2640. }
  2641. return nil, fmt.Errorf("postgres unreachable after %d attempts: %w", len(delays), lastErr)
  2642. }
  2643. // The store holds client secrets, so it and its WAL/SHM side files stay
  2644. // owner-only. Best effort: a store the panel cannot chmod still opens.
  2645. func restrictSQLiteFilePerms(dbPath string) error {
  2646. for _, name := range []string{dbPath, dbPath + "-wal", dbPath + "-shm"} {
  2647. if err := os.Chmod(name, 0o600); err != nil && !errors.Is(err, os.ErrNotExist) {
  2648. return err
  2649. }
  2650. }
  2651. return nil
  2652. }
  2653. func sqliteJournalMode() string {
  2654. switch strings.ToUpper(strings.TrimSpace(os.Getenv("XUI_DB_JOURNAL_MODE"))) {
  2655. case "DELETE":
  2656. return "DELETE"
  2657. default:
  2658. return "WAL"
  2659. }
  2660. }
  2661. func backupSQLiteStepPages() int {
  2662. if sqliteJournalMode() == "DELETE" {
  2663. return 128
  2664. }
  2665. return -1
  2666. }
  2667. func cleanupSQLiteBackupDirs(dir string) error {
  2668. entries, err := os.ReadDir(dir)
  2669. if errors.Is(err, os.ErrNotExist) {
  2670. return nil
  2671. }
  2672. if err != nil {
  2673. return err
  2674. }
  2675. for _, entry := range entries {
  2676. if entry.IsDir() && strings.HasPrefix(entry.Name(), sqliteBackupDirPrefix) {
  2677. if err := os.RemoveAll(filepath.Join(dir, entry.Name())); err != nil {
  2678. return err
  2679. }
  2680. }
  2681. }
  2682. return nil
  2683. }
  2684. func sqliteSynchronous() string {
  2685. switch strings.ToUpper(strings.TrimSpace(os.Getenv("XUI_DB_SYNCHRONOUS"))) {
  2686. case "OFF":
  2687. return "OFF"
  2688. case "NORMAL":
  2689. return "NORMAL"
  2690. case "EXTRA":
  2691. return "EXTRA"
  2692. default:
  2693. return "FULL"
  2694. }
  2695. }
  2696. func envInt(key string, def int) int {
  2697. v := strings.TrimSpace(os.Getenv(key))
  2698. if v == "" {
  2699. return def
  2700. }
  2701. n, err := strconv.Atoi(v)
  2702. if err != nil || n <= 0 {
  2703. return def
  2704. }
  2705. return n
  2706. }
  2707. func CloseDB() error {
  2708. if db != nil {
  2709. sqlDB, err := db.DB()
  2710. if err != nil {
  2711. return err
  2712. }
  2713. return sqlDB.Close()
  2714. }
  2715. return nil
  2716. }
  2717. func GetDB() *gorm.DB {
  2718. return db
  2719. }
  2720. func IsNotFound(err error) bool {
  2721. return errors.Is(err, gorm.ErrRecordNotFound)
  2722. }
  2723. func IsSQLiteDB(file io.ReaderAt) (bool, error) {
  2724. signature := []byte("SQLite format 3\x00")
  2725. buf := make([]byte, len(signature))
  2726. _, err := file.ReadAt(buf, 0)
  2727. if err != nil {
  2728. return false, err
  2729. }
  2730. return bytes.Equal(buf, signature), nil
  2731. }
  2732. func BackupSQLite(dstPath string) (err error) {
  2733. if IsPostgres() {
  2734. return errors.New("sqlite backup is unavailable for PostgreSQL")
  2735. }
  2736. if db == nil {
  2737. return errors.New("database is not initialized")
  2738. }
  2739. if _, err := os.Lstat(dstPath); err == nil {
  2740. return fmt.Errorf("sqlite backup destination already exists: %s", dstPath)
  2741. } else if !errors.Is(err, os.ErrNotExist) {
  2742. return err
  2743. }
  2744. defer func() {
  2745. if err != nil {
  2746. _ = os.Remove(dstPath)
  2747. }
  2748. }()
  2749. ctx, cancel := context.WithTimeout(context.Background(), backupSQLiteTimeout)
  2750. defer cancel()
  2751. sourceDB, err := db.DB()
  2752. if err != nil {
  2753. return err
  2754. }
  2755. sourceConn, err := sourceDB.Conn(ctx)
  2756. if err != nil {
  2757. return err
  2758. }
  2759. defer sourceConn.Close()
  2760. destinationDB, err := sql.Open("sqlite3", dstPath)
  2761. if err != nil {
  2762. return err
  2763. }
  2764. defer destinationDB.Close()
  2765. destinationConn, err := destinationDB.Conn(ctx)
  2766. if err != nil {
  2767. return err
  2768. }
  2769. defer destinationConn.Close()
  2770. return sourceConn.Raw(func(sourceDriver any) error {
  2771. source, ok := sourceDriver.(*sqlite3.SQLiteConn)
  2772. if !ok {
  2773. return fmt.Errorf("unexpected SQLite source connection type %T", sourceDriver)
  2774. }
  2775. return destinationConn.Raw(func(destinationDriver any) error {
  2776. destination, ok := destinationDriver.(*sqlite3.SQLiteConn)
  2777. if !ok {
  2778. return fmt.Errorf("unexpected SQLite destination connection type %T", destinationDriver)
  2779. }
  2780. backup, err := destination.Backup("main", source, "main")
  2781. if err != nil {
  2782. return err
  2783. }
  2784. finished := false
  2785. defer func() {
  2786. if !finished {
  2787. _ = backup.Finish()
  2788. }
  2789. }()
  2790. for {
  2791. done, err := backup.Step(backupSQLiteStepPages())
  2792. if err != nil {
  2793. return err
  2794. }
  2795. if done {
  2796. finished = true
  2797. return backup.Finish()
  2798. }
  2799. select {
  2800. case <-ctx.Done():
  2801. return ctx.Err()
  2802. case <-time.After(10 * time.Millisecond):
  2803. }
  2804. }
  2805. })
  2806. })
  2807. }
  2808. func ValidateSQLiteDB(dbPath string) error {
  2809. if _, err := os.Stat(dbPath); err != nil {
  2810. return err
  2811. }
  2812. gdb, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{Logger: logger.Discard})
  2813. if err != nil {
  2814. return err
  2815. }
  2816. sqlDB, err := gdb.DB()
  2817. if err != nil {
  2818. return err
  2819. }
  2820. defer sqlDB.Close()
  2821. var res string
  2822. if err := gdb.Raw("PRAGMA integrity_check;").Scan(&res).Error; err != nil {
  2823. return err
  2824. }
  2825. if res != "ok" {
  2826. return errors.New("sqlite integrity check failed: " + res)
  2827. }
  2828. return nil
  2829. }