db.go 97 KB

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