db.go 85 KB

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