db.go 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420
  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, 0o700); 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. if err := restrictSQLiteFilePerms(dbPath); err != nil {
  1969. log.Printf("restrict SQLite file permissions: %v", err)
  1970. }
  1971. sqlDB, err := db.DB()
  1972. if err != nil {
  1973. return err
  1974. }
  1975. pragmas := []string{
  1976. "PRAGMA journal_mode=" + journal,
  1977. "PRAGMA busy_timeout=10000",
  1978. "PRAGMA synchronous=" + sync,
  1979. fmt.Sprintf("PRAGMA cache_size=-%d", envInt("XUI_DB_CACHE_MB", 32)*1024),
  1980. fmt.Sprintf("PRAGMA mmap_size=%d", int64(envInt("XUI_DB_MMAP_MB", 256))*1024*1024),
  1981. "PRAGMA temp_store=MEMORY",
  1982. }
  1983. for _, p := range pragmas {
  1984. if _, err := sqlDB.ExecContext(context.Background(), p); err != nil {
  1985. return err
  1986. }
  1987. }
  1988. }
  1989. sqlDB, err := db.DB()
  1990. if err != nil {
  1991. return err
  1992. }
  1993. var maxOpen, maxIdle int
  1994. switch config.GetDBKind() {
  1995. case "postgres":
  1996. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 25)
  1997. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 25)
  1998. default:
  1999. maxOpen = envInt("XUI_DB_MAX_OPEN_CONNS", 8)
  2000. maxIdle = envInt("XUI_DB_MAX_IDLE_CONNS", 4)
  2001. }
  2002. sqlDB.SetMaxOpenConns(maxOpen)
  2003. sqlDB.SetMaxIdleConns(maxIdle)
  2004. sqlDB.SetConnMaxLifetime(time.Hour)
  2005. sqlDB.SetConnMaxIdleTime(30 * time.Minute)
  2006. if err := initModels(); err != nil {
  2007. return err
  2008. }
  2009. isUsersEmpty, err := isTableEmpty("users")
  2010. if err != nil {
  2011. return err
  2012. }
  2013. if isUsersEmpty {
  2014. if err := seedRandomSubscriptionPaths(); err != nil {
  2015. return err
  2016. }
  2017. }
  2018. if err := initUser(); err != nil {
  2019. return err
  2020. }
  2021. return runSeeders(isUsersEmpty)
  2022. }
  2023. func normalizeApiTokenCreatedAtSeconds() error {
  2024. return db.Model(&model.ApiToken{}).
  2025. Where("created_at >= ?", model.ApiTokenUnixMillisecondsThreshold).
  2026. UpdateColumn("created_at", gorm.Expr("created_at / ?", 1000)).Error
  2027. }
  2028. func migrateApiTokenScopeAndExpiry() error {
  2029. m := db.Migrator()
  2030. if !m.HasColumn(&model.ApiToken{}, "Scope") {
  2031. if err := m.AddColumn(&model.ApiToken{}, "Scope"); err != nil {
  2032. return err
  2033. }
  2034. }
  2035. if !m.HasColumn(&model.ApiToken{}, "ExpiresAt") {
  2036. if err := m.AddColumn(&model.ApiToken{}, "ExpiresAt"); err != nil {
  2037. return err
  2038. }
  2039. }
  2040. return db.Model(&model.ApiToken{}).Where("scope IS NULL OR TRIM(scope) = ''").
  2041. Updates(map[string]any{"scope": model.ApiScopeAdmin, "expires_at": 0}).Error
  2042. }
  2043. // openPostgresWithRetry retries the initial PostgreSQL connection with
  2044. // backoff so a database that starts slower than the panel (or drops out
  2045. // briefly) does not immediately kill the process and trip systemd's
  2046. // restart loop. Every failed attempt logs the real driver error, which
  2047. // used to be buried behind a generic startup failure.
  2048. func openPostgresWithRetry(dsn string, c *gorm.Config) (*gorm.DB, error) {
  2049. delays := []time.Duration{0, 2 * time.Second, 5 * time.Second, 10 * time.Second, 20 * time.Second, 30 * time.Second}
  2050. var lastErr error
  2051. for i, delay := range delays {
  2052. if delay > 0 {
  2053. time.Sleep(delay)
  2054. }
  2055. conn, err := gorm.Open(postgres.Open(dsn), c)
  2056. if err == nil {
  2057. if i > 0 {
  2058. log.Printf("postgres connection established on attempt %d/%d", i+1, len(delays))
  2059. }
  2060. return conn, nil
  2061. }
  2062. lastErr = err
  2063. log.Printf("postgres connection attempt %d/%d failed: %v", i+1, len(delays), err)
  2064. }
  2065. return nil, fmt.Errorf("postgres unreachable after %d attempts: %w", len(delays), lastErr)
  2066. }
  2067. // The store holds client secrets, so it and its WAL/SHM side files stay
  2068. // owner-only. Best effort: a store the panel cannot chmod still opens.
  2069. func restrictSQLiteFilePerms(dbPath string) error {
  2070. for _, name := range []string{dbPath, dbPath + "-wal", dbPath + "-shm"} {
  2071. if err := os.Chmod(name, 0o600); err != nil && !errors.Is(err, os.ErrNotExist) {
  2072. return err
  2073. }
  2074. }
  2075. return nil
  2076. }
  2077. func sqliteJournalMode() string {
  2078. switch strings.ToUpper(strings.TrimSpace(os.Getenv("XUI_DB_JOURNAL_MODE"))) {
  2079. case "DELETE":
  2080. return "DELETE"
  2081. default:
  2082. return "WAL"
  2083. }
  2084. }
  2085. func backupSQLiteStepPages() int {
  2086. if sqliteJournalMode() == "DELETE" {
  2087. return 128
  2088. }
  2089. return -1
  2090. }
  2091. func cleanupSQLiteBackupDirs(dir string) error {
  2092. entries, err := os.ReadDir(dir)
  2093. if errors.Is(err, os.ErrNotExist) {
  2094. return nil
  2095. }
  2096. if err != nil {
  2097. return err
  2098. }
  2099. for _, entry := range entries {
  2100. if entry.IsDir() && strings.HasPrefix(entry.Name(), sqliteBackupDirPrefix) {
  2101. if err := os.RemoveAll(filepath.Join(dir, entry.Name())); err != nil {
  2102. return err
  2103. }
  2104. }
  2105. }
  2106. return nil
  2107. }
  2108. func sqliteSynchronous() string {
  2109. switch strings.ToUpper(strings.TrimSpace(os.Getenv("XUI_DB_SYNCHRONOUS"))) {
  2110. case "OFF":
  2111. return "OFF"
  2112. case "NORMAL":
  2113. return "NORMAL"
  2114. case "EXTRA":
  2115. return "EXTRA"
  2116. default:
  2117. return "FULL"
  2118. }
  2119. }
  2120. func envInt(key string, def int) int {
  2121. v := strings.TrimSpace(os.Getenv(key))
  2122. if v == "" {
  2123. return def
  2124. }
  2125. n, err := strconv.Atoi(v)
  2126. if err != nil || n <= 0 {
  2127. return def
  2128. }
  2129. return n
  2130. }
  2131. func CloseDB() error {
  2132. if db != nil {
  2133. sqlDB, err := db.DB()
  2134. if err != nil {
  2135. return err
  2136. }
  2137. return sqlDB.Close()
  2138. }
  2139. return nil
  2140. }
  2141. func GetDB() *gorm.DB {
  2142. return db
  2143. }
  2144. func IsNotFound(err error) bool {
  2145. return errors.Is(err, gorm.ErrRecordNotFound)
  2146. }
  2147. func IsSQLiteDB(file io.ReaderAt) (bool, error) {
  2148. signature := []byte("SQLite format 3\x00")
  2149. buf := make([]byte, len(signature))
  2150. _, err := file.ReadAt(buf, 0)
  2151. if err != nil {
  2152. return false, err
  2153. }
  2154. return bytes.Equal(buf, signature), nil
  2155. }
  2156. func BackupSQLite(dstPath string) (err error) {
  2157. if IsPostgres() {
  2158. return errors.New("sqlite backup is unavailable for PostgreSQL")
  2159. }
  2160. if db == nil {
  2161. return errors.New("database is not initialized")
  2162. }
  2163. if _, err := os.Lstat(dstPath); err == nil {
  2164. return fmt.Errorf("sqlite backup destination already exists: %s", dstPath)
  2165. } else if !errors.Is(err, os.ErrNotExist) {
  2166. return err
  2167. }
  2168. defer func() {
  2169. if err != nil {
  2170. _ = os.Remove(dstPath)
  2171. }
  2172. }()
  2173. ctx, cancel := context.WithTimeout(context.Background(), backupSQLiteTimeout)
  2174. defer cancel()
  2175. sourceDB, err := db.DB()
  2176. if err != nil {
  2177. return err
  2178. }
  2179. sourceConn, err := sourceDB.Conn(ctx)
  2180. if err != nil {
  2181. return err
  2182. }
  2183. defer sourceConn.Close()
  2184. destinationDB, err := sql.Open("sqlite3", dstPath)
  2185. if err != nil {
  2186. return err
  2187. }
  2188. defer destinationDB.Close()
  2189. destinationConn, err := destinationDB.Conn(ctx)
  2190. if err != nil {
  2191. return err
  2192. }
  2193. defer destinationConn.Close()
  2194. return sourceConn.Raw(func(sourceDriver any) error {
  2195. source, ok := sourceDriver.(*sqlite3.SQLiteConn)
  2196. if !ok {
  2197. return fmt.Errorf("unexpected SQLite source connection type %T", sourceDriver)
  2198. }
  2199. return destinationConn.Raw(func(destinationDriver any) error {
  2200. destination, ok := destinationDriver.(*sqlite3.SQLiteConn)
  2201. if !ok {
  2202. return fmt.Errorf("unexpected SQLite destination connection type %T", destinationDriver)
  2203. }
  2204. backup, err := destination.Backup("main", source, "main")
  2205. if err != nil {
  2206. return err
  2207. }
  2208. finished := false
  2209. defer func() {
  2210. if !finished {
  2211. _ = backup.Finish()
  2212. }
  2213. }()
  2214. for {
  2215. done, err := backup.Step(backupSQLiteStepPages())
  2216. if err != nil {
  2217. return err
  2218. }
  2219. if done {
  2220. finished = true
  2221. return backup.Finish()
  2222. }
  2223. select {
  2224. case <-ctx.Done():
  2225. return ctx.Err()
  2226. case <-time.After(10 * time.Millisecond):
  2227. }
  2228. }
  2229. })
  2230. })
  2231. }
  2232. func ValidateSQLiteDB(dbPath string) error {
  2233. if _, err := os.Stat(dbPath); err != nil {
  2234. return err
  2235. }
  2236. gdb, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{Logger: logger.Discard})
  2237. if err != nil {
  2238. return err
  2239. }
  2240. sqlDB, err := gdb.DB()
  2241. if err != nil {
  2242. return err
  2243. }
  2244. defer sqlDB.Close()
  2245. var res string
  2246. if err := gdb.Raw("PRAGMA integrity_check;").Scan(&res).Error; err != nil {
  2247. return err
  2248. }
  2249. if res != "ok" {
  2250. return errors.New("sqlite integrity check failed: " + res)
  2251. }
  2252. return nil
  2253. }