db.go 85 KB

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