1
0

db.go 92 KB

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