db.go 65 KB

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