1
0

db.go 92 KB

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