db.go 84 KB

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