db.go 80 KB

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