db.go 66 KB

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