db.go 97 KB

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