db.go 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406
  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 seedRandomSubscriptionPaths() error {
  1099. settings := []model.Setting{
  1100. {Key: "subPath", Value: "/" + random.NumLower(16) + "/"},
  1101. {Key: "subJsonPath", Value: "/" + random.NumLower(16) + "/"},
  1102. {Key: "subClashPath", Value: "/" + random.NumLower(16) + "/"},
  1103. }
  1104. return db.Transaction(func(tx *gorm.DB) error {
  1105. for i := range settings {
  1106. if err := tx.Where("key = ?", settings[i].Key).FirstOrCreate(&settings[i]).Error; err != nil {
  1107. return err
  1108. }
  1109. }
  1110. return nil
  1111. })
  1112. }
  1113. func runSeeders(isUsersEmpty bool) error {
  1114. empty, err := isTableEmpty("history_of_seeders")
  1115. if err != nil {
  1116. log.Printf("Error checking if users table is empty: %v", err)
  1117. return err
  1118. }
  1119. if empty && isUsersEmpty {
  1120. seeders := []string{"UserPasswordHash", "ClientsTable", "InboundClientsArrayFix", "InboundClientTgIdFix2", "InboundClientSubIdFix", "FreedomFinalRulesReverseFix", "FreedomFinalRulesPrivateEgressBlock", "InboundRealityFinalmaskTcpStrip", "ApiTokensHash", "LegacyProxySettingsCleanup", "WireguardPeersToClients", "MtprotoSecretsToClients", "NodeInboundsAdopted", "ResetIpLimitNoFail2ban"}
  1121. for _, name := range seeders {
  1122. if err := db.Create(&model.HistoryOfSeeders{SeederName: name}).Error; err != nil {
  1123. return err
  1124. }
  1125. }
  1126. return seedApiTokens()
  1127. }
  1128. var seedersHistory []string
  1129. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &seedersHistory).Error; err != nil {
  1130. log.Printf("Error fetching seeder history: %v", err)
  1131. return err
  1132. }
  1133. if !slices.Contains(seedersHistory, "UserPasswordHash") && !isUsersEmpty {
  1134. var users []model.User
  1135. if err := db.Find(&users).Error; err != nil {
  1136. log.Printf("Error fetching users for password migration: %v", err)
  1137. return err
  1138. }
  1139. for _, user := range users {
  1140. if crypto.IsHashed(user.Password) {
  1141. continue
  1142. }
  1143. hashedPassword, err := crypto.HashPasswordAsBcrypt(user.Password)
  1144. if err != nil {
  1145. log.Printf("Error hashing password for user '%s': %v", user.Username, err)
  1146. return err
  1147. }
  1148. if err := db.Model(&user).Update("password", hashedPassword).Error; err != nil {
  1149. log.Printf("Error updating password for user '%s': %v", user.Username, err)
  1150. return err
  1151. }
  1152. }
  1153. hashSeeder := &model.HistoryOfSeeders{
  1154. SeederName: "UserPasswordHash",
  1155. }
  1156. if err := db.Create(hashSeeder).Error; err != nil {
  1157. return err
  1158. }
  1159. }
  1160. if !slices.Contains(seedersHistory, "ApiTokensTable") {
  1161. if err := seedApiTokens(); err != nil {
  1162. return err
  1163. }
  1164. }
  1165. if !slices.Contains(seedersHistory, "ApiTokensHash") {
  1166. if err := hashExistingApiTokens(); err != nil {
  1167. return err
  1168. }
  1169. }
  1170. if !slices.Contains(seedersHistory, "ClientsTable") {
  1171. if err := seedClientsFromInboundJSON(); err != nil {
  1172. return err
  1173. }
  1174. }
  1175. if !slices.Contains(seedersHistory, "InboundClientsArrayFix") {
  1176. if err := normalizeInboundClientsArray(); err != nil {
  1177. return err
  1178. }
  1179. }
  1180. if !slices.Contains(seedersHistory, "InboundClientTgIdFix2") {
  1181. if err := normalizeInboundClientTgId(); err != nil {
  1182. return err
  1183. }
  1184. }
  1185. if !slices.Contains(seedersHistory, "InboundClientSubIdFix") {
  1186. if err := normalizeInboundClientSubId(); err != nil {
  1187. return err
  1188. }
  1189. }
  1190. if !slices.Contains(seedersHistory, "FreedomFinalRulesReverseFix") {
  1191. if err := normalizeFreedomFinalRules(); err != nil {
  1192. return err
  1193. }
  1194. }
  1195. if !slices.Contains(seedersHistory, "FreedomFinalRulesPrivateEgressBlock") {
  1196. if err := hardenFreedomFinalRules(); err != nil {
  1197. return err
  1198. }
  1199. }
  1200. if !slices.Contains(seedersHistory, "InboundRealityFinalmaskTcpStrip") {
  1201. if err := stripRealityFinalmaskTcp(); err != nil {
  1202. return err
  1203. }
  1204. }
  1205. if !slices.Contains(seedersHistory, "LegacyProxySettingsCleanup") {
  1206. if err := clearLegacyProxySettings(); err != nil {
  1207. return err
  1208. }
  1209. }
  1210. if !slices.Contains(seedersHistory, "NodeInboundsAdopted") {
  1211. if err := seedNodeInboundsAdopted(); err != nil {
  1212. return err
  1213. }
  1214. }
  1215. if err := seedHostsFromExternalProxy(); err != nil {
  1216. return err
  1217. }
  1218. if err := resetIpLimitsWithoutFail2ban(); err != nil {
  1219. return err
  1220. }
  1221. if err := seedWireguardPeersToClients(); err != nil {
  1222. return err
  1223. }
  1224. if err := backfillEmptyHostGroupIds(); err != nil {
  1225. return err
  1226. }
  1227. // Self-gated on the "MtprotoSecretsToClients" row.
  1228. if err := seedMtprotoSecretsToClients(); err != nil {
  1229. return err
  1230. }
  1231. // Self-gated on the "StripMtprotoInboundSecrets" row. Must run after the
  1232. // seeder above so legacy single-secret inbounds are first converted to a
  1233. // client (which preserves the secret) before the inbound-level copy is
  1234. // dropped from every mtproto inbound.
  1235. if err := stripMtprotoInboundSecrets(); err != nil {
  1236. return err
  1237. }
  1238. // Idempotent, not seeder-gated: bad values can re-enter via a restored
  1239. // backup, so re-check on every start.
  1240. return normalizeSettingPaths()
  1241. }
  1242. // seedNodeInboundsAdopted keeps the pre-existing reconcile behavior for nodes
  1243. // that were already syncing before the inbounds_adopted_at gate was introduced.
  1244. func seedNodeInboundsAdopted() error {
  1245. if err := db.Model(&model.Node{}).
  1246. Where("inbounds_adopted_at = 0").
  1247. Update("inbounds_adopted_at", time.Now().Unix()).Error; err != nil {
  1248. return err
  1249. }
  1250. return db.Create(&model.HistoryOfSeeders{SeederName: "NodeInboundsAdopted"}).Error
  1251. }
  1252. // backfillEmptyHostGroupIds is idempotent and not seeder-gated: builds that
  1253. // predate group ids on the inbound-import path (and restored backups) can
  1254. // re-introduce hosts rows with an empty group_id, and such rows render as a
  1255. // synthetic fallback_<id> group the update/delete API cannot address, so
  1256. // re-check on every start.
  1257. func backfillEmptyHostGroupIds() error {
  1258. var hosts []*model.Host
  1259. if err := db.Where("group_id = '' OR group_id IS NULL").Find(&hosts).Error; err != nil {
  1260. return err
  1261. }
  1262. if len(hosts) == 0 {
  1263. return nil
  1264. }
  1265. return db.Transaction(func(tx *gorm.DB) error {
  1266. for _, h := range hosts {
  1267. if err := tx.Model(h).Update("group_id", random.NumLower(16)).Error; err != nil {
  1268. return err
  1269. }
  1270. }
  1271. return nil
  1272. })
  1273. }
  1274. func resetIpLimitsWithoutFail2ban() error {
  1275. var history []string
  1276. if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &history).Error; err != nil {
  1277. return err
  1278. }
  1279. if slices.Contains(history, "ResetIpLimitNoFail2ban") {
  1280. return nil
  1281. }
  1282. state, probeErr := fail2banEnforcementState()
  1283. if state == fail2banEnforcing {
  1284. return db.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
  1285. }
  1286. if state == fail2banUnknown {
  1287. log.Printf("ResetIpLimitNoFail2ban: fail2ban-client present but not runnable (%v); keeping configured IP limits, will retry next start", probeErr)
  1288. return nil
  1289. }
  1290. var inbounds []model.Inbound
  1291. if err := db.Find(&inbounds).Error; err != nil {
  1292. return err
  1293. }
  1294. return db.Transaction(func(tx *gorm.DB) error {
  1295. for _, inbound := range inbounds {
  1296. if strings.TrimSpace(inbound.Settings) == "" {
  1297. continue
  1298. }
  1299. var settings map[string]any
  1300. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1301. log.Printf("ResetIpLimitNoFail2ban: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1302. continue
  1303. }
  1304. clients, ok := settings["clients"].([]any)
  1305. if !ok {
  1306. continue
  1307. }
  1308. mutated := false
  1309. for i, raw := range clients {
  1310. obj, ok := raw.(map[string]any)
  1311. if !ok {
  1312. continue
  1313. }
  1314. v, present := obj["limitIp"]
  1315. if !present {
  1316. continue
  1317. }
  1318. if n, isNum := v.(float64); isNum && n == 0 {
  1319. continue
  1320. }
  1321. obj["limitIp"] = 0
  1322. clients[i] = obj
  1323. mutated = true
  1324. }
  1325. if !mutated {
  1326. continue
  1327. }
  1328. settings["clients"] = clients
  1329. newSettings, err := json.MarshalIndent(settings, "", " ")
  1330. if err != nil {
  1331. log.Printf("ResetIpLimitNoFail2ban: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1332. continue
  1333. }
  1334. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1335. Update("settings", string(newSettings)).Error; err != nil {
  1336. return err
  1337. }
  1338. }
  1339. if err := tx.Model(&model.ClientRecord{}).Where("limit_ip <> ?", 0).
  1340. Update("limit_ip", 0).Error; err != nil {
  1341. return err
  1342. }
  1343. return tx.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error
  1344. })
  1345. }
  1346. type fail2banState int
  1347. const (
  1348. fail2banEnforcing fail2banState = iota
  1349. fail2banAbsent
  1350. fail2banUnknown
  1351. )
  1352. // fail2banEnforcementState separates "fail2ban is not installed" from "the probe
  1353. // itself failed", so a transient failure never drives an irreversible cleanup.
  1354. func fail2banEnforcementState() (fail2banState, error) {
  1355. if v, ok := os.LookupEnv("XUI_ENABLE_FAIL2BAN"); ok && v != "true" {
  1356. return fail2banAbsent, nil
  1357. }
  1358. if runtime.GOOS == "windows" {
  1359. return fail2banAbsent, nil
  1360. }
  1361. if _, err := exec.LookPath("fail2ban-client"); err != nil {
  1362. return fail2banAbsent, nil
  1363. }
  1364. if err := exec.CommandContext(context.Background(), "fail2ban-client", "-h").Run(); err != nil {
  1365. return fail2banUnknown, err
  1366. }
  1367. return fail2banEnforcing, nil
  1368. }
  1369. func clearLegacyProxySettings() error {
  1370. return db.Transaction(func(tx *gorm.DB) error {
  1371. if err := tx.Where("key IN ?", []string{"panelProxy", "tgBotProxy"}).
  1372. Delete(&model.Setting{}).Error; err != nil {
  1373. return err
  1374. }
  1375. return tx.Create(&model.HistoryOfSeeders{SeederName: "LegacyProxySettingsCleanup"}).Error
  1376. })
  1377. }
  1378. func normalizeSettingPaths() error {
  1379. pathKeys := []string{"webBasePath", "subPath", "subJsonPath", "subClashPath"}
  1380. var rows []model.Setting
  1381. if err := db.Where("key IN ?", pathKeys).Find(&rows).Error; err != nil {
  1382. return err
  1383. }
  1384. for _, row := range rows {
  1385. fixed := row.Value
  1386. if !strings.HasPrefix(fixed, "/") {
  1387. fixed = "/" + fixed
  1388. }
  1389. if !strings.HasSuffix(fixed, "/") {
  1390. fixed += "/"
  1391. }
  1392. if fixed == row.Value {
  1393. continue
  1394. }
  1395. if err := db.Model(&model.Setting{}).Where("id = ?", row.Id).
  1396. Update("value", fixed).Error; err != nil {
  1397. return err
  1398. }
  1399. }
  1400. return nil
  1401. }
  1402. func normalizeInboundClientTgId() error {
  1403. var inbounds []model.Inbound
  1404. if err := db.Find(&inbounds).Error; err != nil {
  1405. return err
  1406. }
  1407. return db.Transaction(func(tx *gorm.DB) error {
  1408. for _, inbound := range inbounds {
  1409. if strings.TrimSpace(inbound.Settings) == "" {
  1410. continue
  1411. }
  1412. var settings map[string]any
  1413. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1414. log.Printf("InboundClientTgIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1415. continue
  1416. }
  1417. clients, ok := settings["clients"].([]any)
  1418. if !ok {
  1419. continue
  1420. }
  1421. mutated := false
  1422. for i, raw := range clients {
  1423. obj, ok := raw.(map[string]any)
  1424. if !ok {
  1425. continue
  1426. }
  1427. tgRaw, present := obj["tgId"]
  1428. if !present {
  1429. continue
  1430. }
  1431. v, isFloat := tgRaw.(float64)
  1432. if isFloat && !math.IsNaN(v) && !math.IsInf(v, 0) && v == math.Trunc(v) {
  1433. continue
  1434. }
  1435. obj["tgId"] = int64(0)
  1436. if s, isStr := tgRaw.(string); isStr {
  1437. if id, err := strconv.ParseInt(strings.ReplaceAll(strings.TrimSpace(s), " ", ""), 10, 64); err == nil {
  1438. obj["tgId"] = id
  1439. }
  1440. }
  1441. clients[i] = obj
  1442. mutated = true
  1443. }
  1444. if !mutated {
  1445. continue
  1446. }
  1447. settings["clients"] = clients
  1448. newSettings, err := json.MarshalIndent(settings, "", " ")
  1449. if err != nil {
  1450. log.Printf("InboundClientTgIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1451. continue
  1452. }
  1453. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1454. Update("settings", string(newSettings)).Error; err != nil {
  1455. return err
  1456. }
  1457. }
  1458. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientTgIdFix2"}).Error
  1459. })
  1460. }
  1461. func normalizeInboundClientSubId() error {
  1462. var inbounds []model.Inbound
  1463. if err := db.Find(&inbounds).Error; err != nil {
  1464. return err
  1465. }
  1466. return db.Transaction(func(tx *gorm.DB) error {
  1467. for _, inbound := range inbounds {
  1468. if strings.TrimSpace(inbound.Settings) == "" {
  1469. continue
  1470. }
  1471. var settings map[string]any
  1472. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1473. log.Printf("InboundClientSubIdFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1474. continue
  1475. }
  1476. clients, ok := settings["clients"].([]any)
  1477. if !ok {
  1478. continue
  1479. }
  1480. mutated := false
  1481. for i, raw := range clients {
  1482. obj, ok := raw.(map[string]any)
  1483. if !ok {
  1484. continue
  1485. }
  1486. existing, _ := obj["subId"].(string)
  1487. if strings.TrimSpace(existing) != "" {
  1488. continue
  1489. }
  1490. obj["subId"] = random.NumLower(16)
  1491. clients[i] = obj
  1492. mutated = true
  1493. }
  1494. if !mutated {
  1495. continue
  1496. }
  1497. settings["clients"] = clients
  1498. newSettings, err := json.MarshalIndent(settings, "", " ")
  1499. if err != nil {
  1500. log.Printf("InboundClientSubIdFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1501. continue
  1502. }
  1503. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1504. Update("settings", string(newSettings)).Error; err != nil {
  1505. return err
  1506. }
  1507. }
  1508. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientSubIdFix"}).Error
  1509. })
  1510. }
  1511. func normalizeInboundClientsArray() error {
  1512. var inbounds []model.Inbound
  1513. if err := db.Find(&inbounds).Error; err != nil {
  1514. return err
  1515. }
  1516. return db.Transaction(func(tx *gorm.DB) error {
  1517. for _, inbound := range inbounds {
  1518. if strings.TrimSpace(inbound.Settings) == "" {
  1519. continue
  1520. }
  1521. var settings map[string]any
  1522. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1523. log.Printf("InboundClientsArrayFix: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1524. continue
  1525. }
  1526. raw, exists := settings["clients"]
  1527. if !exists || raw != nil {
  1528. continue
  1529. }
  1530. settings["clients"] = []any{}
  1531. newSettings, err := json.MarshalIndent(settings, "", " ")
  1532. if err != nil {
  1533. log.Printf("InboundClientsArrayFix: skip inbound %d (marshal failed): %v", inbound.Id, err)
  1534. continue
  1535. }
  1536. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
  1537. Update("settings", string(newSettings)).Error; err != nil {
  1538. return err
  1539. }
  1540. }
  1541. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundClientsArrayFix"}).Error
  1542. })
  1543. }
  1544. func normalizeFreedomFinalRules() error {
  1545. var setting model.Setting
  1546. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  1547. if errors.Is(err, gorm.ErrRecordNotFound) {
  1548. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  1549. }
  1550. if err != nil {
  1551. return err
  1552. }
  1553. updated, changed, rErr := rewriteFreedomFinalRules(setting.Value)
  1554. if rErr != nil {
  1555. log.Printf("FreedomFinalRulesReverseFix: skip (invalid xrayTemplateConfig json): %v", rErr)
  1556. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  1557. }
  1558. return db.Transaction(func(tx *gorm.DB) error {
  1559. if changed {
  1560. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  1561. Update("value", updated).Error; err != nil {
  1562. return err
  1563. }
  1564. }
  1565. return tx.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesReverseFix"}).Error
  1566. })
  1567. }
  1568. func rewriteFreedomFinalRules(raw string) (string, bool, error) {
  1569. if strings.TrimSpace(raw) == "" {
  1570. return raw, false, nil
  1571. }
  1572. var cfg map[string]any
  1573. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  1574. return raw, false, err
  1575. }
  1576. outbounds, ok := cfg["outbounds"].([]any)
  1577. if !ok {
  1578. return raw, false, nil
  1579. }
  1580. changed := false
  1581. for _, ob := range outbounds {
  1582. obj, ok := ob.(map[string]any)
  1583. if !ok {
  1584. continue
  1585. }
  1586. if proto, _ := obj["protocol"].(string); proto != "freedom" {
  1587. continue
  1588. }
  1589. settings, ok := obj["settings"].(map[string]any)
  1590. if !ok {
  1591. continue
  1592. }
  1593. if !isLegacyPrivateOnlyFinalRules(settings["finalRules"]) {
  1594. continue
  1595. }
  1596. settings["finalRules"] = []any{map[string]any{"action": "allow"}}
  1597. changed = true
  1598. }
  1599. if !changed {
  1600. return raw, false, nil
  1601. }
  1602. out, err := json.MarshalIndent(cfg, "", " ")
  1603. if err != nil {
  1604. return raw, false, err
  1605. }
  1606. return string(out), true, nil
  1607. }
  1608. func isLegacyPrivateOnlyFinalRules(v any) bool {
  1609. rules, ok := v.([]any)
  1610. if !ok || len(rules) != 1 {
  1611. return false
  1612. }
  1613. rule, ok := rules[0].(map[string]any)
  1614. if !ok {
  1615. return false
  1616. }
  1617. if action, _ := rule["action"].(string); action != "allow" {
  1618. return false
  1619. }
  1620. ips, ok := rule["ip"].([]any)
  1621. if !ok || len(ips) != 1 {
  1622. return false
  1623. }
  1624. if s, _ := ips[0].(string); s != "geoip:private" {
  1625. return false
  1626. }
  1627. for k := range rule {
  1628. if k != "action" && k != "ip" {
  1629. return false
  1630. }
  1631. }
  1632. return true
  1633. }
  1634. func isUnrestrictedFreedomFinalRules(v any, present bool) bool {
  1635. if !present || v == nil {
  1636. return true
  1637. }
  1638. rules, ok := v.([]any)
  1639. return ok && len(rules) == 0
  1640. }
  1641. func hardenFreedomFinalRules() error {
  1642. var setting model.Setting
  1643. err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
  1644. if errors.Is(err, gorm.ErrRecordNotFound) {
  1645. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesPrivateEgressBlock"}).Error
  1646. }
  1647. if err != nil {
  1648. return err
  1649. }
  1650. updated, changed, rErr := rewriteFreedomFinalRulesPrivateEgress(setting.Value)
  1651. if rErr != nil {
  1652. log.Printf("FreedomFinalRulesPrivateEgressBlock: skip (invalid xrayTemplateConfig json): %v", rErr)
  1653. return db.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesPrivateEgressBlock"}).Error
  1654. }
  1655. return db.Transaction(func(tx *gorm.DB) error {
  1656. if changed {
  1657. if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
  1658. Update("value", updated).Error; err != nil {
  1659. return err
  1660. }
  1661. }
  1662. return tx.Create(&model.HistoryOfSeeders{SeederName: "FreedomFinalRulesPrivateEgressBlock"}).Error
  1663. })
  1664. }
  1665. func rewriteFreedomFinalRulesPrivateEgress(raw string) (string, bool, error) {
  1666. if strings.TrimSpace(raw) == "" {
  1667. return raw, false, nil
  1668. }
  1669. var cfg map[string]any
  1670. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  1671. return raw, false, err
  1672. }
  1673. outbounds, ok := cfg["outbounds"].([]any)
  1674. if !ok {
  1675. return raw, false, nil
  1676. }
  1677. changed := false
  1678. for _, ob := range outbounds {
  1679. obj, ok := ob.(map[string]any)
  1680. if !ok {
  1681. continue
  1682. }
  1683. if proto, _ := obj["protocol"].(string); proto != "freedom" {
  1684. continue
  1685. }
  1686. settings, ok := obj["settings"].(map[string]any)
  1687. if !ok {
  1688. continue
  1689. }
  1690. finalRules, present := settings["finalRules"]
  1691. if !isUnrestrictedFreedomFinalRules(finalRules, present) &&
  1692. !isAllowOnlyFinalRules(finalRules) &&
  1693. !isLegacyPrivateOnlyFinalRules(finalRules) {
  1694. continue
  1695. }
  1696. settings["finalRules"] = []any{
  1697. map[string]any{"action": "block", "ip": []any{"geoip:private"}},
  1698. map[string]any{"action": "allow"},
  1699. }
  1700. changed = true
  1701. }
  1702. if !changed {
  1703. return raw, false, nil
  1704. }
  1705. out, err := json.MarshalIndent(cfg, "", " ")
  1706. if err != nil {
  1707. return raw, false, err
  1708. }
  1709. return string(out), true, nil
  1710. }
  1711. func stripRealityFinalmaskTcp() error {
  1712. var inbounds []model.Inbound
  1713. if err := db.Find(&inbounds).Error; err != nil {
  1714. return err
  1715. }
  1716. return db.Transaction(func(tx *gorm.DB) error {
  1717. for i := range inbounds {
  1718. updated, changed := stripRealityFinalmaskTcpFromStream(inbounds[i].StreamSettings)
  1719. if !changed {
  1720. continue
  1721. }
  1722. if err := tx.Model(&model.Inbound{}).Where("id = ?", inbounds[i].Id).
  1723. Update("stream_settings", updated).Error; err != nil {
  1724. return err
  1725. }
  1726. log.Printf("InboundRealityFinalmaskTcpStrip: removed finalmask.tcp from REALITY inbound %d (%s)", inbounds[i].Id, inbounds[i].Tag)
  1727. }
  1728. return tx.Create(&model.HistoryOfSeeders{SeederName: "InboundRealityFinalmaskTcpStrip"}).Error
  1729. })
  1730. }
  1731. func stripRealityFinalmaskTcpFromStream(raw string) (string, bool) {
  1732. if strings.TrimSpace(raw) == "" {
  1733. return raw, false
  1734. }
  1735. var stream map[string]any
  1736. if err := json.Unmarshal([]byte(raw), &stream); err != nil {
  1737. return raw, false
  1738. }
  1739. if sec, _ := stream["security"].(string); sec != "reality" {
  1740. return raw, false
  1741. }
  1742. finalmask, ok := stream["finalmask"].(map[string]any)
  1743. if !ok {
  1744. return raw, false
  1745. }
  1746. if tcp, _ := finalmask["tcp"].([]any); len(tcp) == 0 {
  1747. return raw, false
  1748. }
  1749. delete(finalmask, "tcp")
  1750. if len(finalmask) == 0 {
  1751. delete(stream, "finalmask")
  1752. }
  1753. out, err := json.Marshal(stream)
  1754. if err != nil {
  1755. return raw, false
  1756. }
  1757. return string(out), true
  1758. }
  1759. func isAllowOnlyFinalRules(v any) bool {
  1760. rules, ok := v.([]any)
  1761. if !ok || len(rules) != 1 {
  1762. return false
  1763. }
  1764. rule, ok := rules[0].(map[string]any)
  1765. if !ok {
  1766. return false
  1767. }
  1768. if action, _ := rule["action"].(string); action != "allow" {
  1769. return false
  1770. }
  1771. for k := range rule {
  1772. if k != "action" {
  1773. return false
  1774. }
  1775. }
  1776. return true
  1777. }
  1778. func normalizeClientJSONFields(obj map[string]any) {
  1779. normalizeInt := func(key string) {
  1780. raw, exists := obj[key]
  1781. if !exists {
  1782. return
  1783. }
  1784. s, ok := raw.(string)
  1785. if !ok {
  1786. return
  1787. }
  1788. trimmed := strings.ReplaceAll(strings.TrimSpace(s), " ", "")
  1789. if trimmed == "" {
  1790. delete(obj, key)
  1791. return
  1792. }
  1793. if n, err := strconv.ParseInt(trimmed, 10, 64); err == nil {
  1794. obj[key] = n
  1795. } else {
  1796. delete(obj, key)
  1797. }
  1798. }
  1799. for _, k := range []string{"tgId", "limitIp", "totalGB", "expiryTime", "reset", "created_at", "updated_at"} {
  1800. normalizeInt(k)
  1801. }
  1802. }
  1803. func seedClientsFromInboundJSON() error {
  1804. var inbounds []model.Inbound
  1805. if err := db.Find(&inbounds).Error; err != nil {
  1806. return err
  1807. }
  1808. return db.Transaction(func(tx *gorm.DB) error {
  1809. byEmail := map[string]*model.ClientRecord{}
  1810. var existing []model.ClientRecord
  1811. if err := tx.Find(&existing).Error; err != nil {
  1812. return err
  1813. }
  1814. for i := range existing {
  1815. byEmail[existing[i].Email] = &existing[i]
  1816. }
  1817. for _, inbound := range inbounds {
  1818. if strings.TrimSpace(inbound.Settings) == "" {
  1819. continue
  1820. }
  1821. var settings map[string]any
  1822. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1823. log.Printf("ClientsTable seed: skip inbound %d (invalid settings json): %v", inbound.Id, err)
  1824. continue
  1825. }
  1826. rawList, ok := settings["clients"].([]any)
  1827. if !ok {
  1828. continue
  1829. }
  1830. for _, raw := range rawList {
  1831. obj, ok := raw.(map[string]any)
  1832. if !ok {
  1833. continue
  1834. }
  1835. normalizeClientJSONFields(obj)
  1836. blob, err := json.Marshal(obj)
  1837. if err != nil {
  1838. continue
  1839. }
  1840. var c model.Client
  1841. if err := json.Unmarshal(blob, &c); err != nil {
  1842. log.Printf("ClientsTable seed: skip client in inbound %d (unmarshal failed): %v; payload=%s",
  1843. inbound.Id, err, string(blob))
  1844. continue
  1845. }
  1846. email := strings.TrimSpace(c.Email)
  1847. if email == "" {
  1848. continue
  1849. }
  1850. incoming := c.ToRecord()
  1851. row, dup := byEmail[email]
  1852. if !dup {
  1853. if err := tx.Create(incoming).Error; err != nil {
  1854. return err
  1855. }
  1856. byEmail[email] = incoming
  1857. row = incoming
  1858. } else {
  1859. conflicts := model.MergeClientRecord(row, incoming)
  1860. for _, x := range conflicts {
  1861. log.Printf("client merge: email=%s conflict on %s old=%v new=%v kept=%v",
  1862. email, x.Field, x.Old, x.New, x.Kept)
  1863. }
  1864. if err := tx.Save(row).Error; err != nil {
  1865. return err
  1866. }
  1867. }
  1868. link := model.ClientInbound{
  1869. ClientId: row.Id,
  1870. InboundId: inbound.Id,
  1871. FlowOverride: c.Flow,
  1872. }
  1873. if err := tx.Where("client_id = ? AND inbound_id = ?", row.Id, inbound.Id).
  1874. FirstOrCreate(&link).Error; err != nil {
  1875. return err
  1876. }
  1877. }
  1878. }
  1879. return tx.Create(&model.HistoryOfSeeders{SeederName: "ClientsTable"}).Error
  1880. })
  1881. }
  1882. func seedApiTokens() error {
  1883. empty, err := isTableEmpty("api_tokens")
  1884. if err != nil {
  1885. return err
  1886. }
  1887. if empty {
  1888. var legacy model.Setting
  1889. err := db.Model(model.Setting{}).Where("key = ?", "apiToken").First(&legacy).Error
  1890. if err == nil && legacy.Value != "" {
  1891. row := &model.ApiToken{
  1892. Name: "default",
  1893. Token: legacy.Value,
  1894. Enabled: true,
  1895. }
  1896. if err := db.Create(row).Error; err != nil {
  1897. log.Printf("Error migrating legacy apiToken: %v", err)
  1898. return err
  1899. }
  1900. }
  1901. }
  1902. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensTable"}).Error
  1903. }
  1904. func hashExistingApiTokens() error {
  1905. var rows []*model.ApiToken
  1906. if err := db.Find(&rows).Error; err != nil {
  1907. return err
  1908. }
  1909. for _, r := range rows {
  1910. if crypto.IsSHA256Hex(r.Token) {
  1911. continue
  1912. }
  1913. hashed := crypto.HashTokenSHA256(r.Token)
  1914. if err := db.Model(model.ApiToken{}).Where("id = ?", r.Id).Update("token", hashed).Error; err != nil {
  1915. log.Printf("Error hashing api token %d: %v", r.Id, err)
  1916. return err
  1917. }
  1918. }
  1919. return db.Create(&model.HistoryOfSeeders{SeederName: "ApiTokensHash"}).Error
  1920. }
  1921. func isTableEmpty(tableName string) (bool, error) {
  1922. var count int64
  1923. err := db.Table(tableName).Count(&count).Error
  1924. return count == 0, err
  1925. }
  1926. func InitDB(dbPath string) error {
  1927. var gormLogger logger.Interface
  1928. if config.IsDebug() {
  1929. gormLogger = logger.New(
  1930. log.New(os.Stdout, "\r\n", log.LstdFlags),
  1931. logger.Config{
  1932. SlowThreshold: time.Second,
  1933. LogLevel: logger.Info,
  1934. IgnoreRecordNotFoundError: true,
  1935. Colorful: true,
  1936. },
  1937. )
  1938. } else {
  1939. gormLogger = logger.Discard
  1940. }
  1941. c := &gorm.Config{Logger: gormLogger, DisableForeignKeyConstraintWhenMigrating: true}
  1942. var err error
  1943. switch config.GetDBKind() {
  1944. case "postgres":
  1945. dsn := config.GetDBDSN()
  1946. if dsn == "" {
  1947. return errors.New("XUI_DB_TYPE=postgres but XUI_DB_DSN is empty")
  1948. }
  1949. db, err = openPostgresWithRetry(dsn, c)
  1950. if err != nil {
  1951. return err
  1952. }
  1953. default:
  1954. dir := path.Dir(dbPath)
  1955. if err = os.MkdirAll(dir, 0o755); err != nil {
  1956. return err
  1957. }
  1958. if err = cleanupSQLiteBackupDirs(filepath.Dir(dbPath)); err != nil {
  1959. log.Printf("clean SQLite backup directories: %v", err)
  1960. }
  1961. sync := sqliteSynchronous()
  1962. journal := sqliteJournalMode()
  1963. dsn := dbPath + "?_journal_mode=" + journal + "&_busy_timeout=10000&_synchronous=" + sync + "&_txlock=immediate"
  1964. db, err = gorm.Open(sqlite.Open(dsn), c)
  1965. if err != nil {
  1966. return err
  1967. }
  1968. sqlDB, err := db.DB()
  1969. if err != nil {
  1970. return err
  1971. }
  1972. pragmas := []string{
  1973. "PRAGMA journal_mode=" + journal,
  1974. "PRAGMA busy_timeout=10000",
  1975. "PRAGMA synchronous=" + sync,
  1976. fmt.Sprintf("PRAGMA cache_size=-%d", envInt("XUI_DB_CACHE_MB", 32)*1024),
  1977. fmt.Sprintf("PRAGMA mmap_size=%d", int64(envInt("XUI_DB_MMAP_MB", 256))*1024*1024),
  1978. "PRAGMA temp_store=MEMORY",
  1979. }
  1980. for _, p := range pragmas {
  1981. if _, err := sqlDB.ExecContext(context.Background(), p); err != nil {
  1982. return err
  1983. }
  1984. }
  1985. }
  1986. sqlDB, err := db.DB()
  1987. if err != nil {
  1988. return err
  1989. }
  1990. var maxOpen, maxIdle int
  1991. switch config.GetDBKind() {
  1992. case "postgres":
  1993. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 25)
  1994. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 25)
  1995. default:
  1996. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 8)
  1997. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 4)
  1998. }
  1999. sqlDB.SetMaxOpenConns(maxOpen)
  2000. sqlDB.SetMaxIdleConns(maxIdle)
  2001. sqlDB.SetConnMaxLifetime(time.Hour)
  2002. sqlDB.SetConnMaxIdleTime(30 * time.Minute)
  2003. if err := initModels(); err != nil {
  2004. return err
  2005. }
  2006. isUsersEmpty, err := isTableEmpty("users")
  2007. if err != nil {
  2008. return err
  2009. }
  2010. if isUsersEmpty {
  2011. if err := seedRandomSubscriptionPaths(); err != nil {
  2012. return err
  2013. }
  2014. }
  2015. if err := initUser(); err != nil {
  2016. return err
  2017. }
  2018. return runSeeders(isUsersEmpty)
  2019. }
  2020. func normalizeApiTokenCreatedAtSeconds() error {
  2021. return db.Model(&model.ApiToken{}).
  2022. Where("created_at >= ?", model.ApiTokenUnixMillisecondsThreshold).
  2023. UpdateColumn("created_at", gorm.Expr("created_at / ?", 1000)).Error
  2024. }
  2025. func migrateApiTokenScopeAndExpiry() error {
  2026. m := db.Migrator()
  2027. if !m.HasColumn(&model.ApiToken{}, "Scope") {
  2028. if err := m.AddColumn(&model.ApiToken{}, "Scope"); err != nil {
  2029. return err
  2030. }
  2031. }
  2032. if !m.HasColumn(&model.ApiToken{}, "ExpiresAt") {
  2033. if err := m.AddColumn(&model.ApiToken{}, "ExpiresAt"); err != nil {
  2034. return err
  2035. }
  2036. }
  2037. return db.Model(&model.ApiToken{}).Where("scope IS NULL OR TRIM(scope) = ''").
  2038. Updates(map[string]any{"scope": model.ApiScopeAdmin, "expires_at": 0}).Error
  2039. }
  2040. // openPostgresWithRetry retries the initial PostgreSQL connection with
  2041. // backoff so a database that starts slower than the panel (or drops out
  2042. // briefly) does not immediately kill the process and trip systemd's
  2043. // restart loop. Every failed attempt logs the real driver error, which
  2044. // used to be buried behind a generic startup failure.
  2045. func openPostgresWithRetry(dsn string, c *gorm.Config) (*gorm.DB, error) {
  2046. delays := []time.Duration{0, 2 * time.Second, 5 * time.Second, 10 * time.Second, 20 * time.Second, 30 * time.Second}
  2047. var lastErr error
  2048. for i, delay := range delays {
  2049. if delay > 0 {
  2050. time.Sleep(delay)
  2051. }
  2052. conn, err := gorm.Open(postgres.Open(dsn), c)
  2053. if err == nil {
  2054. if i > 0 {
  2055. log.Printf("postgres connection established on attempt %d/%d", i+1, len(delays))
  2056. }
  2057. return conn, nil
  2058. }
  2059. lastErr = err
  2060. log.Printf("postgres connection attempt %d/%d failed: %v", i+1, len(delays), err)
  2061. }
  2062. return nil, fmt.Errorf("postgres unreachable after %d attempts: %w", len(delays), lastErr)
  2063. }
  2064. func sqliteJournalMode() string {
  2065. switch strings.ToUpper(strings.TrimSpace(os.Getenv("XUI_DB_JOURNAL_MODE"))) {
  2066. case "DELETE":
  2067. return "DELETE"
  2068. default:
  2069. return "WAL"
  2070. }
  2071. }
  2072. func backupSQLiteStepPages() int {
  2073. if sqliteJournalMode() == "DELETE" {
  2074. return 128
  2075. }
  2076. return -1
  2077. }
  2078. func cleanupSQLiteBackupDirs(dir string) error {
  2079. entries, err := os.ReadDir(dir)
  2080. if errors.Is(err, os.ErrNotExist) {
  2081. return nil
  2082. }
  2083. if err != nil {
  2084. return err
  2085. }
  2086. for _, entry := range entries {
  2087. if entry.IsDir() && strings.HasPrefix(entry.Name(), sqliteBackupDirPrefix) {
  2088. if err := os.RemoveAll(filepath.Join(dir, entry.Name())); err != nil {
  2089. return err
  2090. }
  2091. }
  2092. }
  2093. return nil
  2094. }
  2095. func sqliteSynchronous() string {
  2096. switch strings.ToUpper(strings.TrimSpace(os.Getenv("XUI_DB_SYNCHRONOUS"))) {
  2097. case "OFF":
  2098. return "OFF"
  2099. case "NORMAL":
  2100. return "NORMAL"
  2101. case "EXTRA":
  2102. return "EXTRA"
  2103. default:
  2104. return "FULL"
  2105. }
  2106. }
  2107. func envInt(key string, def int) int {
  2108. v := strings.TrimSpace(os.Getenv(key))
  2109. if v == "" {
  2110. return def
  2111. }
  2112. n, err := strconv.Atoi(v)
  2113. if err != nil || n <= 0 {
  2114. return def
  2115. }
  2116. return n
  2117. }
  2118. func CloseDB() error {
  2119. if db != nil {
  2120. sqlDB, err := db.DB()
  2121. if err != nil {
  2122. return err
  2123. }
  2124. return sqlDB.Close()
  2125. }
  2126. return nil
  2127. }
  2128. func GetDB() *gorm.DB {
  2129. return db
  2130. }
  2131. func IsNotFound(err error) bool {
  2132. return errors.Is(err, gorm.ErrRecordNotFound)
  2133. }
  2134. func IsSQLiteDB(file io.ReaderAt) (bool, error) {
  2135. signature := []byte("SQLite format 3\x00")
  2136. buf := make([]byte, len(signature))
  2137. _, err := file.ReadAt(buf, 0)
  2138. if err != nil {
  2139. return false, err
  2140. }
  2141. return bytes.Equal(buf, signature), nil
  2142. }
  2143. func BackupSQLite(dstPath string) (err error) {
  2144. if IsPostgres() {
  2145. return errors.New("sqlite backup is unavailable for PostgreSQL")
  2146. }
  2147. if db == nil {
  2148. return errors.New("database is not initialized")
  2149. }
  2150. if _, err := os.Lstat(dstPath); err == nil {
  2151. return fmt.Errorf("sqlite backup destination already exists: %s", dstPath)
  2152. } else if !errors.Is(err, os.ErrNotExist) {
  2153. return err
  2154. }
  2155. defer func() {
  2156. if err != nil {
  2157. _ = os.Remove(dstPath)
  2158. }
  2159. }()
  2160. ctx, cancel := context.WithTimeout(context.Background(), backupSQLiteTimeout)
  2161. defer cancel()
  2162. sourceDB, err := db.DB()
  2163. if err != nil {
  2164. return err
  2165. }
  2166. sourceConn, err := sourceDB.Conn(ctx)
  2167. if err != nil {
  2168. return err
  2169. }
  2170. defer sourceConn.Close()
  2171. destinationDB, err := sql.Open("sqlite3", dstPath)
  2172. if err != nil {
  2173. return err
  2174. }
  2175. defer destinationDB.Close()
  2176. destinationConn, err := destinationDB.Conn(ctx)
  2177. if err != nil {
  2178. return err
  2179. }
  2180. defer destinationConn.Close()
  2181. return sourceConn.Raw(func(sourceDriver any) error {
  2182. source, ok := sourceDriver.(*sqlite3.SQLiteConn)
  2183. if !ok {
  2184. return fmt.Errorf("unexpected SQLite source connection type %T", sourceDriver)
  2185. }
  2186. return destinationConn.Raw(func(destinationDriver any) error {
  2187. destination, ok := destinationDriver.(*sqlite3.SQLiteConn)
  2188. if !ok {
  2189. return fmt.Errorf("unexpected SQLite destination connection type %T", destinationDriver)
  2190. }
  2191. backup, err := destination.Backup("main", source, "main")
  2192. if err != nil {
  2193. return err
  2194. }
  2195. finished := false
  2196. defer func() {
  2197. if !finished {
  2198. _ = backup.Finish()
  2199. }
  2200. }()
  2201. for {
  2202. done, err := backup.Step(backupSQLiteStepPages())
  2203. if err != nil {
  2204. return err
  2205. }
  2206. if done {
  2207. finished = true
  2208. return backup.Finish()
  2209. }
  2210. select {
  2211. case <-ctx.Done():
  2212. return ctx.Err()
  2213. case <-time.After(10 * time.Millisecond):
  2214. }
  2215. }
  2216. })
  2217. })
  2218. }
  2219. func ValidateSQLiteDB(dbPath string) error {
  2220. if _, err := os.Stat(dbPath); err != nil {
  2221. return err
  2222. }
  2223. gdb, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{Logger: logger.Discard})
  2224. if err != nil {
  2225. return err
  2226. }
  2227. sqlDB, err := gdb.DB()
  2228. if err != nil {
  2229. return err
  2230. }
  2231. defer sqlDB.Close()
  2232. var res string
  2233. if err := gdb.Raw("PRAGMA integrity_check;").Scan(&res).Error; err != nil {
  2234. return err
  2235. }
  2236. if res != "ok" {
  2237. return errors.New("sqlite integrity check failed: " + res)
  2238. }
  2239. return nil
  2240. }