db.go 95 KB

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